id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
19,300
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/table/MTable.java
MTable.addColumn
public MTable<T> addColumn(final String attribute, final String libelle) { final int modelIndex = getColumnCount(); final TableColumn tableColumn = new TableColumn(modelIndex); // on met l'énumération de l'attribut comme identifier dans le TableColumn pour s'en servir dans MTableModel tableColumn.setIdentifier(attribute); if (libelle == null) { // on prend par défaut l'attribut si le libellé n'est pas précisé, tableColumn.setHeaderValue(attribute); } else { // le libellé a été précisé pour l'entête de cette colonne tableColumn.setHeaderValue(libelle); } // ajoute la colonne dans la table super.addColumn(tableColumn); return this; }
java
public MTable<T> addColumn(final String attribute, final String libelle) { final int modelIndex = getColumnCount(); final TableColumn tableColumn = new TableColumn(modelIndex); // on met l'énumération de l'attribut comme identifier dans le TableColumn pour s'en servir dans MTableModel tableColumn.setIdentifier(attribute); if (libelle == null) { // on prend par défaut l'attribut si le libellé n'est pas précisé, tableColumn.setHeaderValue(attribute); } else { // le libellé a été précisé pour l'entête de cette colonne tableColumn.setHeaderValue(libelle); } // ajoute la colonne dans la table super.addColumn(tableColumn); return this; }
[ "public", "MTable", "<", "T", ">", "addColumn", "(", "final", "String", "attribute", ",", "final", "String", "libelle", ")", "{", "final", "int", "modelIndex", "=", "getColumnCount", "(", ")", ";", "final", "TableColumn", "tableColumn", "=", "new", "TableColumn", "(", "modelIndex", ")", ";", "// on met l'énumération de l'attribut comme identifier dans le TableColumn pour s'en servir dans MTableModel\r", "tableColumn", ".", "setIdentifier", "(", "attribute", ")", ";", "if", "(", "libelle", "==", "null", ")", "{", "// on prend par défaut l'attribut si le libellé n'est pas précisé,\r", "tableColumn", ".", "setHeaderValue", "(", "attribute", ")", ";", "}", "else", "{", "// le libellé a été précisé pour l'entête de cette colonne\r", "tableColumn", ".", "setHeaderValue", "(", "libelle", ")", ";", "}", "// ajoute la colonne dans la table\r", "super", ".", "addColumn", "(", "tableColumn", ")", ";", "return", "this", ";", "}" ]
Ajoute une colonne dans la table. @param attribute Nom de l'attribut des objets à afficher dans la colonne<br/> @param libelle Libellé à afficher en entête de la colonne @return this (fluent)
[ "Ajoute", "une", "colonne", "dans", "la", "table", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/table/MTable.java#L118-L133
19,301
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/pdf/PdfMBeansReport.java
PdfMBeansReport.writeTree
void writeTree() throws DocumentException { // MBeans pour la plateforme margin = 0; final MBeanNode platformNode = mbeans.get(0); writeTree(platformNode.getChildren()); for (final MBeanNode node : mbeans) { if (node != platformNode) { newPage(); addToDocument(new Chunk(node.getName(), boldFont)); margin = 0; writeTree(node.getChildren()); } } }
java
void writeTree() throws DocumentException { // MBeans pour la plateforme margin = 0; final MBeanNode platformNode = mbeans.get(0); writeTree(platformNode.getChildren()); for (final MBeanNode node : mbeans) { if (node != platformNode) { newPage(); addToDocument(new Chunk(node.getName(), boldFont)); margin = 0; writeTree(node.getChildren()); } } }
[ "void", "writeTree", "(", ")", "throws", "DocumentException", "{", "// MBeans pour la plateforme\r", "margin", "=", "0", ";", "final", "MBeanNode", "platformNode", "=", "mbeans", ".", "get", "(", "0", ")", ";", "writeTree", "(", "platformNode", ".", "getChildren", "(", ")", ")", ";", "for", "(", "final", "MBeanNode", "node", ":", "mbeans", ")", "{", "if", "(", "node", "!=", "platformNode", ")", "{", "newPage", "(", ")", ";", "addToDocument", "(", "new", "Chunk", "(", "node", ".", "getName", "(", ")", ",", "boldFont", ")", ")", ";", "margin", "=", "0", ";", "writeTree", "(", "node", ".", "getChildren", "(", ")", ")", ";", "}", "}", "}" ]
Affiche l'arbre des MBeans. @throws DocumentException e
[ "Affiche", "l", "arbre", "des", "MBeans", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/pdf/PdfMBeansReport.java#L62-L76
19,302
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/util/MSwingUtilities.java
MSwingUtilities.getScaledInstance
public static ImageIcon getScaledInstance(ImageIcon icon, int targetWidth, int targetHeight) { return new ImageIcon(getScaledInstance(icon.getImage(), targetWidth, targetHeight)); }
java
public static ImageIcon getScaledInstance(ImageIcon icon, int targetWidth, int targetHeight) { return new ImageIcon(getScaledInstance(icon.getImage(), targetWidth, targetHeight)); }
[ "public", "static", "ImageIcon", "getScaledInstance", "(", "ImageIcon", "icon", ",", "int", "targetWidth", ",", "int", "targetHeight", ")", "{", "return", "new", "ImageIcon", "(", "getScaledInstance", "(", "icon", ".", "getImage", "(", ")", ",", "targetWidth", ",", "targetHeight", ")", ")", ";", "}" ]
Redimensionne une ImageIcon. @param icon ImageIcon @param targetWidth int @param targetHeight int @return ImageIcon
[ "Redimensionne", "une", "ImageIcon", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/util/MSwingUtilities.java#L217-L219
19,303
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/util/MSwingUtilities.java
MSwingUtilities.getScaledInstance
public static Image getScaledInstance(Image img, int targetWidth, int targetHeight) { final int type = BufferedImage.TYPE_INT_ARGB; Image ret = img; final int width = ret.getWidth(null); final int height = ret.getHeight(null); if (width != targetWidth && height != targetHeight) { // a priori plus performant que Image.getScaledInstance final BufferedImage scratchImage = new BufferedImage(targetWidth, targetHeight, type); final Graphics2D g2 = scratchImage.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(ret, 0, 0, targetWidth, targetHeight, 0, 0, width, height, null); g2.dispose(); ret = scratchImage; } return ret; }
java
public static Image getScaledInstance(Image img, int targetWidth, int targetHeight) { final int type = BufferedImage.TYPE_INT_ARGB; Image ret = img; final int width = ret.getWidth(null); final int height = ret.getHeight(null); if (width != targetWidth && height != targetHeight) { // a priori plus performant que Image.getScaledInstance final BufferedImage scratchImage = new BufferedImage(targetWidth, targetHeight, type); final Graphics2D g2 = scratchImage.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(ret, 0, 0, targetWidth, targetHeight, 0, 0, width, height, null); g2.dispose(); ret = scratchImage; } return ret; }
[ "public", "static", "Image", "getScaledInstance", "(", "Image", "img", ",", "int", "targetWidth", ",", "int", "targetHeight", ")", "{", "final", "int", "type", "=", "BufferedImage", ".", "TYPE_INT_ARGB", ";", "Image", "ret", "=", "img", ";", "final", "int", "width", "=", "ret", ".", "getWidth", "(", "null", ")", ";", "final", "int", "height", "=", "ret", ".", "getHeight", "(", "null", ")", ";", "if", "(", "width", "!=", "targetWidth", "&&", "height", "!=", "targetHeight", ")", "{", "// a priori plus performant que Image.getScaledInstance\r", "final", "BufferedImage", "scratchImage", "=", "new", "BufferedImage", "(", "targetWidth", ",", "targetHeight", ",", "type", ")", ";", "final", "Graphics2D", "g2", "=", "scratchImage", ".", "createGraphics", "(", ")", ";", "g2", ".", "setRenderingHint", "(", "RenderingHints", ".", "KEY_INTERPOLATION", ",", "RenderingHints", ".", "VALUE_INTERPOLATION_BILINEAR", ")", ";", "g2", ".", "drawImage", "(", "ret", ",", "0", ",", "0", ",", "targetWidth", ",", "targetHeight", ",", "0", ",", "0", ",", "width", ",", "height", ",", "null", ")", ";", "g2", ".", "dispose", "(", ")", ";", "ret", "=", "scratchImage", ";", "}", "return", "ret", ";", "}" ]
Redimensionne une image. @param img Image @param targetWidth int @param targetHeight int @return Image
[ "Redimensionne", "une", "image", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/util/MSwingUtilities.java#L228-L244
19,304
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/TransportFormatAdapter.java
TransportFormatAdapter.writeXml
public static void writeXml(Serializable serializable, OutputStream output) throws IOException { TransportFormat.XML.writeSerializableTo(serializable, output); }
java
public static void writeXml(Serializable serializable, OutputStream output) throws IOException { TransportFormat.XML.writeSerializableTo(serializable, output); }
[ "public", "static", "void", "writeXml", "(", "Serializable", "serializable", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "TransportFormat", ".", "XML", ".", "writeSerializableTo", "(", "serializable", ",", "output", ")", ";", "}" ]
Export XML. @param serializable Serializable @param output OutputStream @throws IOException e
[ "Export", "XML", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/TransportFormatAdapter.java#L41-L43
19,305
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/TransportFormatAdapter.java
TransportFormatAdapter.writeJson
public static void writeJson(Serializable serializable, OutputStream output) throws IOException { TransportFormat.JSON.writeSerializableTo(serializable, output); }
java
public static void writeJson(Serializable serializable, OutputStream output) throws IOException { TransportFormat.JSON.writeSerializableTo(serializable, output); }
[ "public", "static", "void", "writeJson", "(", "Serializable", "serializable", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "TransportFormat", ".", "JSON", ".", "writeSerializableTo", "(", "serializable", ",", "output", ")", ";", "}" ]
Export JSON. @param serializable Serializable @param output OutputStream @throws IOException e
[ "Export", "JSON", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/TransportFormatAdapter.java#L51-L54
19,306
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/Main.java
Main.initLookAndFeel
private static void initLookAndFeel() { // UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); for (final LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { try { UIManager.setLookAndFeel(info.getClassName()); break; } catch (final Exception e) { throw new RuntimeException(e); // NOPMD } } } }
java
private static void initLookAndFeel() { // UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); for (final LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { try { UIManager.setLookAndFeel(info.getClassName()); break; } catch (final Exception e) { throw new RuntimeException(e); // NOPMD } } } }
[ "private", "static", "void", "initLookAndFeel", "(", ")", "{", "// UIManager.setLookAndFeel(\"javax.swing.plaf.nimbus.NimbusLookAndFeel\");\r", "for", "(", "final", "LookAndFeelInfo", "info", ":", "UIManager", ".", "getInstalledLookAndFeels", "(", ")", ")", "{", "if", "(", "\"Nimbus\"", ".", "equals", "(", "info", ".", "getName", "(", ")", ")", ")", "{", "try", "{", "UIManager", ".", "setLookAndFeel", "(", "info", ".", "getClassName", "(", ")", ")", ";", "break", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "// NOPMD\r", "}", "}", "}", "}" ]
Initialisation du L&F.
[ "Initialisation", "du", "L&F", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/Main.java#L144-L156
19,307
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/common/I18N.java
I18N.getResourceBundle
public static ResourceBundle getResourceBundle() { final Locale currentLocale = getCurrentLocale(); if (Locale.ENGLISH.getLanguage().equals(currentLocale.getLanguage())) { // there is no translations_en.properties because translations.properties is in English // but if user is English, do not let getBundle fallback on server's default locale return ResourceBundle.getBundle(RESOURCE_BUNDLE_BASE_NAME, ROOT_LOCALE); } // and if user is not English, use the bundle if it exists for his/her Locale // or the bundle for the server's default locale if it exists // or default (English) bundle otherwise return ResourceBundle.getBundle(RESOURCE_BUNDLE_BASE_NAME, currentLocale); }
java
public static ResourceBundle getResourceBundle() { final Locale currentLocale = getCurrentLocale(); if (Locale.ENGLISH.getLanguage().equals(currentLocale.getLanguage())) { // there is no translations_en.properties because translations.properties is in English // but if user is English, do not let getBundle fallback on server's default locale return ResourceBundle.getBundle(RESOURCE_BUNDLE_BASE_NAME, ROOT_LOCALE); } // and if user is not English, use the bundle if it exists for his/her Locale // or the bundle for the server's default locale if it exists // or default (English) bundle otherwise return ResourceBundle.getBundle(RESOURCE_BUNDLE_BASE_NAME, currentLocale); }
[ "public", "static", "ResourceBundle", "getResourceBundle", "(", ")", "{", "final", "Locale", "currentLocale", "=", "getCurrentLocale", "(", ")", ";", "if", "(", "Locale", ".", "ENGLISH", ".", "getLanguage", "(", ")", ".", "equals", "(", "currentLocale", ".", "getLanguage", "(", ")", ")", ")", "{", "// there is no translations_en.properties because translations.properties is in English\r", "// but if user is English, do not let getBundle fallback on server's default locale\r", "return", "ResourceBundle", ".", "getBundle", "(", "RESOURCE_BUNDLE_BASE_NAME", ",", "ROOT_LOCALE", ")", ";", "}", "// and if user is not English, use the bundle if it exists for his/her Locale\r", "// or the bundle for the server's default locale if it exists\r", "// or default (English) bundle otherwise\r", "return", "ResourceBundle", ".", "getBundle", "(", "RESOURCE_BUNDLE_BASE_NAME", ",", "currentLocale", ")", ";", "}" ]
Retourne les traductions pour la locale courante. @return Locale
[ "Retourne", "les", "traductions", "pour", "la", "locale", "courante", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/common/I18N.java#L82-L93
19,308
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/common/I18N.java
I18N.getStringForJavascript
public static String getStringForJavascript(String key) { final String string = getString(key); // ici, le résultat ne contient pas de valeur variable ni d'attaque puisque ce sont des messages internes et fixes, // donc pas besoin d'encoder avec javascriptEncode, et on conserve les apostrophes lisibles dans les messages return string.replace("\\", "\\\\").replace("\n", "\\n").replace("\"", "\\\"").replace("'", "\\'"); }
java
public static String getStringForJavascript(String key) { final String string = getString(key); // ici, le résultat ne contient pas de valeur variable ni d'attaque puisque ce sont des messages internes et fixes, // donc pas besoin d'encoder avec javascriptEncode, et on conserve les apostrophes lisibles dans les messages return string.replace("\\", "\\\\").replace("\n", "\\n").replace("\"", "\\\"").replace("'", "\\'"); }
[ "public", "static", "String", "getStringForJavascript", "(", "String", "key", ")", "{", "final", "String", "string", "=", "getString", "(", "key", ")", ";", "// ici, le résultat ne contient pas de valeur variable ni d'attaque puisque ce sont des messages internes et fixes,\r", "// donc pas besoin d'encoder avec javascriptEncode, et on conserve les apostrophes lisibles dans les messages\r", "return", "string", ".", "replace", "(", "\"\\\\\"", ",", "\"\\\\\\\\\"", ")", ".", "replace", "(", "\"\\n\"", ",", "\"\\\\n\"", ")", ".", "replace", "(", "\"\\\"\"", ",", "\"\\\\\\\"\"", ")", ".", "replace", "(", "\"'\"", ",", "\"\\\\'\"", ")", ";", "}" ]
Retourne une traduction dans la locale courante et l'encode pour affichage en javascript. @param key clé d'un libellé dans les fichiers de traduction @return String
[ "Retourne", "une", "traduction", "dans", "la", "locale", "courante", "et", "l", "encode", "pour", "affichage", "en", "javascript", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/common/I18N.java#L116-L122
19,309
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/common/I18N.java
I18N.htmlEncode
public static String htmlEncode(String text, boolean encodeSpace) { // ces encodages html sont incomplets mais suffisants pour le monitoring String result = text.replaceAll("[&]", "&amp;").replaceAll("[<]", "&lt;") .replaceAll("[>]", "&gt;").replaceAll("[\n]", "<br/>"); if (encodeSpace) { result = result.replaceAll(" ", "&nbsp;"); } return result; }
java
public static String htmlEncode(String text, boolean encodeSpace) { // ces encodages html sont incomplets mais suffisants pour le monitoring String result = text.replaceAll("[&]", "&amp;").replaceAll("[<]", "&lt;") .replaceAll("[>]", "&gt;").replaceAll("[\n]", "<br/>"); if (encodeSpace) { result = result.replaceAll(" ", "&nbsp;"); } return result; }
[ "public", "static", "String", "htmlEncode", "(", "String", "text", ",", "boolean", "encodeSpace", ")", "{", "// ces encodages html sont incomplets mais suffisants pour le monitoring\r", "String", "result", "=", "text", ".", "replaceAll", "(", "\"[&]\"", ",", "\"&amp;\"", ")", ".", "replaceAll", "(", "\"[<]\"", ",", "\"&lt;\"", ")", ".", "replaceAll", "(", "\"[>]\"", ",", "\"&gt;\"", ")", ".", "replaceAll", "(", "\"[\\n]\"", ",", "\"<br/>\"", ")", ";", "if", "(", "encodeSpace", ")", "{", "result", "=", "result", ".", "replaceAll", "(", "\" \"", ",", "\"&nbsp;\"", ")", ";", "}", "return", "result", ";", "}" ]
Encode pour affichage en html. @param text message à encoder @param encodeSpace booléen selon que les espaces sont encodés en nbsp (insécables) @return String
[ "Encode", "pour", "affichage", "en", "html", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/common/I18N.java#L156-L164
19,310
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/Counter.java
Counter.readFromFile
void readFromFile() throws IOException { final Counter counter = new CounterStorage(this).readFromFile(); if (counter != null) { final Counter newCounter = clone(); startDate = counter.getStartDate(); requests.clear(); for (final CounterRequest request : counter.getRequests()) { requests.put(request.getName(), request); } if (errors != null) { errors.clear(); errors.addAll(counter.getErrors()); } // on ajoute les nouvelles requêtes enregistrées avant de lire le fichier // (par ex. les premières requêtes collectées par le serveur de collecte lors de l'initialisation) addRequestsAndErrors(newCounter); } }
java
void readFromFile() throws IOException { final Counter counter = new CounterStorage(this).readFromFile(); if (counter != null) { final Counter newCounter = clone(); startDate = counter.getStartDate(); requests.clear(); for (final CounterRequest request : counter.getRequests()) { requests.put(request.getName(), request); } if (errors != null) { errors.clear(); errors.addAll(counter.getErrors()); } // on ajoute les nouvelles requêtes enregistrées avant de lire le fichier // (par ex. les premières requêtes collectées par le serveur de collecte lors de l'initialisation) addRequestsAndErrors(newCounter); } }
[ "void", "readFromFile", "(", ")", "throws", "IOException", "{", "final", "Counter", "counter", "=", "new", "CounterStorage", "(", "this", ")", ".", "readFromFile", "(", ")", ";", "if", "(", "counter", "!=", "null", ")", "{", "final", "Counter", "newCounter", "=", "clone", "(", ")", ";", "startDate", "=", "counter", ".", "getStartDate", "(", ")", ";", "requests", ".", "clear", "(", ")", ";", "for", "(", "final", "CounterRequest", "request", ":", "counter", ".", "getRequests", "(", ")", ")", "{", "requests", ".", "put", "(", "request", ".", "getName", "(", ")", ",", "request", ")", ";", "}", "if", "(", "errors", "!=", "null", ")", "{", "errors", ".", "clear", "(", ")", ";", "errors", ".", "addAll", "(", "counter", ".", "getErrors", "(", ")", ")", ";", "}", "// on ajoute les nouvelles requêtes enregistrées avant de lire le fichier\r", "// (par ex. les premières requêtes collectées par le serveur de collecte lors de l'initialisation)\r", "addRequestsAndErrors", "(", "newCounter", ")", ";", "}", "}" ]
Lecture du counter depuis son fichier. @throws IOException e
[ "Lecture", "du", "counter", "depuis", "son", "fichier", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/Counter.java#L935-L952
19,311
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPrinter.java
MPrinter.chooseFile
protected File chooseFile(final JTable table, final String extension) throws IOException { final JFileChooser myFileChooser = getFileChooser(); final MExtensionFileFilter filter = new MExtensionFileFilter(extension); myFileChooser.addChoosableFileFilter(filter); String title = buildTitle(table); if (title != null) { // on remplace par des espaces les caractères interdits dans les noms de fichiers : \ / : * ? " < > | final String notAllowed = "\\/:*?\"<>|"; final int notAllowedLength = notAllowed.length(); for (int i = 0; i < notAllowedLength; i++) { title = title.replace(notAllowed.charAt(i), ' '); } myFileChooser.setSelectedFile(new File(title)); } // l'extension sera ajoutée ci-dessous au nom du fichier try { final Component parent = table.getParent() != null ? table.getParent() : table; if (myFileChooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { String fileName = myFileChooser.getSelectedFile().getCanonicalPath(); if (!fileName.endsWith('.' + extension)) { fileName += '.' + extension; // NOPMD } return new File(fileName); } return null; } finally { myFileChooser.removeChoosableFileFilter(filter); } }
java
protected File chooseFile(final JTable table, final String extension) throws IOException { final JFileChooser myFileChooser = getFileChooser(); final MExtensionFileFilter filter = new MExtensionFileFilter(extension); myFileChooser.addChoosableFileFilter(filter); String title = buildTitle(table); if (title != null) { // on remplace par des espaces les caractères interdits dans les noms de fichiers : \ / : * ? " < > | final String notAllowed = "\\/:*?\"<>|"; final int notAllowedLength = notAllowed.length(); for (int i = 0; i < notAllowedLength; i++) { title = title.replace(notAllowed.charAt(i), ' '); } myFileChooser.setSelectedFile(new File(title)); } // l'extension sera ajoutée ci-dessous au nom du fichier try { final Component parent = table.getParent() != null ? table.getParent() : table; if (myFileChooser.showSaveDialog(parent) == JFileChooser.APPROVE_OPTION) { String fileName = myFileChooser.getSelectedFile().getCanonicalPath(); if (!fileName.endsWith('.' + extension)) { fileName += '.' + extension; // NOPMD } return new File(fileName); } return null; } finally { myFileChooser.removeChoosableFileFilter(filter); } }
[ "protected", "File", "chooseFile", "(", "final", "JTable", "table", ",", "final", "String", "extension", ")", "throws", "IOException", "{", "final", "JFileChooser", "myFileChooser", "=", "getFileChooser", "(", ")", ";", "final", "MExtensionFileFilter", "filter", "=", "new", "MExtensionFileFilter", "(", "extension", ")", ";", "myFileChooser", ".", "addChoosableFileFilter", "(", "filter", ")", ";", "String", "title", "=", "buildTitle", "(", "table", ")", ";", "if", "(", "title", "!=", "null", ")", "{", "// on remplace par des espaces les caractères interdits dans les noms de fichiers : \\ / : * ? \" < > |\r", "final", "String", "notAllowed", "=", "\"\\\\/:*?\\\"<>|\"", ";", "final", "int", "notAllowedLength", "=", "notAllowed", ".", "length", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "notAllowedLength", ";", "i", "++", ")", "{", "title", "=", "title", ".", "replace", "(", "notAllowed", ".", "charAt", "(", "i", ")", ",", "'", "'", ")", ";", "}", "myFileChooser", ".", "setSelectedFile", "(", "new", "File", "(", "title", ")", ")", ";", "}", "// l'extension sera ajoutée ci-dessous au nom du fichier\r", "try", "{", "final", "Component", "parent", "=", "table", ".", "getParent", "(", ")", "!=", "null", "?", "table", ".", "getParent", "(", ")", ":", "table", ";", "if", "(", "myFileChooser", ".", "showSaveDialog", "(", "parent", ")", "==", "JFileChooser", ".", "APPROVE_OPTION", ")", "{", "String", "fileName", "=", "myFileChooser", ".", "getSelectedFile", "(", ")", ".", "getCanonicalPath", "(", ")", ";", "if", "(", "!", "fileName", ".", "endsWith", "(", "'", "'", "+", "extension", ")", ")", "{", "fileName", "+=", "'", "'", "+", "extension", ";", "// NOPMD\r", "}", "return", "new", "File", "(", "fileName", ")", ";", "}", "return", "null", ";", "}", "finally", "{", "myFileChooser", ".", "removeChoosableFileFilter", "(", "filter", ")", ";", "}", "}" ]
Choix du fichier pour un export. @return File @param table JTable @param extension String @throws IOException Erreur disque
[ "Choix", "du", "fichier", "pour", "un", "export", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPrinter.java#L152-L184
19,312
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/util/MWaitCursor.java
MWaitCursor.restore
public void restore() { if (window instanceof RootPaneContainer) { final Component glassPane = ((RootPaneContainer) window).getGlassPane(); glassPane.setVisible(windowGlassPaneVisible); glassPane.setCursor(oldWindowCursor); } if (window != null) { window.setCursor(oldWindowCursor); } }
java
public void restore() { if (window instanceof RootPaneContainer) { final Component glassPane = ((RootPaneContainer) window).getGlassPane(); glassPane.setVisible(windowGlassPaneVisible); glassPane.setCursor(oldWindowCursor); } if (window != null) { window.setCursor(oldWindowCursor); } }
[ "public", "void", "restore", "(", ")", "{", "if", "(", "window", "instanceof", "RootPaneContainer", ")", "{", "final", "Component", "glassPane", "=", "(", "(", "RootPaneContainer", ")", "window", ")", ".", "getGlassPane", "(", ")", ";", "glassPane", ".", "setVisible", "(", "windowGlassPaneVisible", ")", ";", "glassPane", ".", "setCursor", "(", "oldWindowCursor", ")", ";", "}", "if", "(", "window", "!=", "null", ")", "{", "window", ".", "setCursor", "(", "oldWindowCursor", ")", ";", "}", "}" ]
Restore l'ancien curseur, en fin de traitement.
[ "Restore", "l", "ancien", "curseur", "en", "fin", "de", "traitement", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/util/MWaitCursor.java#L67-L76
19,313
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/MonitoringGuiceInterceptor.java
MonitoringGuiceInterceptor.getRequestName
protected String getRequestName(MethodInvocation invocation) { final String classPart = getClassPart(invocation); final String methodPart = getMethodPart(invocation); return classPart + '.' + methodPart; }
java
protected String getRequestName(MethodInvocation invocation) { final String classPart = getClassPart(invocation); final String methodPart = getMethodPart(invocation); return classPart + '.' + methodPart; }
[ "protected", "String", "getRequestName", "(", "MethodInvocation", "invocation", ")", "{", "final", "String", "classPart", "=", "getClassPart", "(", "invocation", ")", ";", "final", "String", "methodPart", "=", "getMethodPart", "(", "invocation", ")", ";", "return", "classPart", "+", "'", "'", "+", "methodPart", ";", "}" ]
Determine request name for a method invocation. @param invocation the method invocation (not null) @return the request name for this invocation
[ "Determine", "request", "name", "for", "a", "method", "invocation", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/MonitoringGuiceInterceptor.java#L91-L95
19,314
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackend.java
RrdNioBackend.write
@Override protected synchronized void write(long offset, byte[] b) throws IOException { if (byteBuffer != null) { byteBuffer.position((int) offset); byteBuffer.put(b); } else { throw new IOException("Write failed, file " + getPath() + " not mapped for I/O"); } }
java
@Override protected synchronized void write(long offset, byte[] b) throws IOException { if (byteBuffer != null) { byteBuffer.position((int) offset); byteBuffer.put(b); } else { throw new IOException("Write failed, file " + getPath() + " not mapped for I/O"); } }
[ "@", "Override", "protected", "synchronized", "void", "write", "(", "long", "offset", ",", "byte", "[", "]", "b", ")", "throws", "IOException", "{", "if", "(", "byteBuffer", "!=", "null", ")", "{", "byteBuffer", ".", "position", "(", "(", "int", ")", "offset", ")", ";", "byteBuffer", ".", "put", "(", "b", ")", ";", "}", "else", "{", "throw", "new", "IOException", "(", "\"Write failed, file \"", "+", "getPath", "(", ")", "+", "\" not mapped for I/O\"", ")", ";", "}", "}" ]
Writes bytes to the underlying RRD file on the disk @param offset Starting file offset @param b Bytes to be written.
[ "Writes", "bytes", "to", "the", "underlying", "RRD", "file", "on", "the", "disk" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackend.java#L171-L179
19,315
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackend.java
RrdNioBackend.read
@Override protected synchronized void read(long offset, byte[] b) throws IOException { if (byteBuffer != null) { byteBuffer.position((int) offset); byteBuffer.get(b); } else { throw new IOException("Read failed, file " + getPath() + " not mapped for I/O"); } }
java
@Override protected synchronized void read(long offset, byte[] b) throws IOException { if (byteBuffer != null) { byteBuffer.position((int) offset); byteBuffer.get(b); } else { throw new IOException("Read failed, file " + getPath() + " not mapped for I/O"); } }
[ "@", "Override", "protected", "synchronized", "void", "read", "(", "long", "offset", ",", "byte", "[", "]", "b", ")", "throws", "IOException", "{", "if", "(", "byteBuffer", "!=", "null", ")", "{", "byteBuffer", ".", "position", "(", "(", "int", ")", "offset", ")", ";", "byteBuffer", ".", "get", "(", "b", ")", ";", "}", "else", "{", "throw", "new", "IOException", "(", "\"Read failed, file \"", "+", "getPath", "(", ")", "+", "\" not mapped for I/O\"", ")", ";", "}", "}" ]
Reads a number of bytes from the RRD file on the disk @param offset Starting file offset @param b Buffer which receives bytes read from the file.
[ "Reads", "a", "number", "of", "bytes", "from", "the", "RRD", "file", "on", "the", "disk" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackend.java#L187-L195
19,316
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackend.java
RrdNioBackend.close
@Override public synchronized void close() throws IOException { // cancel synchronization try { if (syncTask != null) { syncTask.cancel(); } sync(); unmapFile(); } finally { super.close(); } }
java
@Override public synchronized void close() throws IOException { // cancel synchronization try { if (syncTask != null) { syncTask.cancel(); } sync(); unmapFile(); } finally { super.close(); } }
[ "@", "Override", "public", "synchronized", "void", "close", "(", ")", "throws", "IOException", "{", "// cancel synchronization\r", "try", "{", "if", "(", "syncTask", "!=", "null", ")", "{", "syncTask", ".", "cancel", "(", ")", ";", "}", "sync", "(", ")", ";", "unmapFile", "(", ")", ";", "}", "finally", "{", "super", ".", "close", "(", ")", ";", "}", "}" ]
Closes the underlying RRD file. @throws IOException Thrown in case of I/O error
[ "Closes", "the", "underlying", "RRD", "file", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackend.java#L202-L214
19,317
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/util/ShadowPopupFactory.java
ShadowPopupFactory.uninstall
public static void uninstall() { final PopupFactory factory = PopupFactory.getSharedInstance(); if (!(factory instanceof ShadowPopupFactory)) { return; } final PopupFactory stored = ((ShadowPopupFactory) factory).storedFactory; PopupFactory.setSharedInstance(stored); }
java
public static void uninstall() { final PopupFactory factory = PopupFactory.getSharedInstance(); if (!(factory instanceof ShadowPopupFactory)) { return; } final PopupFactory stored = ((ShadowPopupFactory) factory).storedFactory; PopupFactory.setSharedInstance(stored); }
[ "public", "static", "void", "uninstall", "(", ")", "{", "final", "PopupFactory", "factory", "=", "PopupFactory", ".", "getSharedInstance", "(", ")", ";", "if", "(", "!", "(", "factory", "instanceof", "ShadowPopupFactory", ")", ")", "{", "return", ";", "}", "final", "PopupFactory", "stored", "=", "(", "(", "ShadowPopupFactory", ")", "factory", ")", ".", "storedFactory", ";", "PopupFactory", ".", "setSharedInstance", "(", "stored", ")", ";", "}" ]
Uninstalls the ShadowPopupFactory and restores the original popup factory as the new shared popup factory. @see #install()
[ "Uninstalls", "the", "ShadowPopupFactory", "and", "restores", "the", "original", "popup", "factory", "as", "the", "new", "shared", "popup", "factory", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/util/ShadowPopupFactory.java#L118-L126
19,318
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java
PrometheusController.report
void report(boolean includeLastValue) throws IOException { // see https://prometheus.io/docs/instrumenting/exposition_formats/ for text format // memory reportOnMemoryInformations(javaInformations.getMemoryInformations()); // jvm & system reportOnJavaInformations(); // tomcat if (javaInformations.getTomcatInformationsList() != null) { reportOnTomcatInformations(); } // caches if (javaInformations.isCacheEnabled()) { reportOnCacheInformations(); } reportOnCollector(); if (includeLastValue) { reportOnLastValues(); } }
java
void report(boolean includeLastValue) throws IOException { // see https://prometheus.io/docs/instrumenting/exposition_formats/ for text format // memory reportOnMemoryInformations(javaInformations.getMemoryInformations()); // jvm & system reportOnJavaInformations(); // tomcat if (javaInformations.getTomcatInformationsList() != null) { reportOnTomcatInformations(); } // caches if (javaInformations.isCacheEnabled()) { reportOnCacheInformations(); } reportOnCollector(); if (includeLastValue) { reportOnLastValues(); } }
[ "void", "report", "(", "boolean", "includeLastValue", ")", "throws", "IOException", "{", "// see https://prometheus.io/docs/instrumenting/exposition_formats/ for text format\r", "// memory\r", "reportOnMemoryInformations", "(", "javaInformations", ".", "getMemoryInformations", "(", ")", ")", ";", "// jvm & system\r", "reportOnJavaInformations", "(", ")", ";", "// tomcat\r", "if", "(", "javaInformations", ".", "getTomcatInformationsList", "(", ")", "!=", "null", ")", "{", "reportOnTomcatInformations", "(", ")", ";", "}", "// caches\r", "if", "(", "javaInformations", ".", "isCacheEnabled", "(", ")", ")", "{", "reportOnCacheInformations", "(", ")", ";", "}", "reportOnCollector", "(", ")", ";", "if", "(", "includeLastValue", ")", "{", "reportOnLastValues", "(", ")", ";", "}", "}" ]
Produce the full report. @param includeLastValue boolean @throws IOException e
[ "Produce", "the", "full", "report", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java#L211-L234
19,319
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java
PrometheusController.reportOnCollector
private void reportOnCollector() { for (final Counter counter : collector.getCounters()) { if (!counter.isDisplayed()) { continue; } final List<CounterRequest> requests = counter.getRequests(); long hits = 0; long duration = 0; long errors = 0; for (final CounterRequest cr : requests) { hits += cr.getHits(); duration += cr.getDurationsSum(); errors += cr.getSystemErrors(); } final String sanitizedName = sanitizeName(counter.getName()); printLong(MetricType.COUNTER, sanitizedName + "_hits_count", "javamelody counter", hits); if (!counter.isErrorCounter() || counter.isJobCounter()) { // errors has no sense for the error and log counters printLong(MetricType.COUNTER, sanitizedName + "_errors_count", "javamelody counter", errors); } if (duration >= 0) { // duration is negative and has no sense for the log counter printLong(MetricType.COUNTER, sanitizedName + "_duration_millis", "javamelody counter", duration); } } }
java
private void reportOnCollector() { for (final Counter counter : collector.getCounters()) { if (!counter.isDisplayed()) { continue; } final List<CounterRequest> requests = counter.getRequests(); long hits = 0; long duration = 0; long errors = 0; for (final CounterRequest cr : requests) { hits += cr.getHits(); duration += cr.getDurationsSum(); errors += cr.getSystemErrors(); } final String sanitizedName = sanitizeName(counter.getName()); printLong(MetricType.COUNTER, sanitizedName + "_hits_count", "javamelody counter", hits); if (!counter.isErrorCounter() || counter.isJobCounter()) { // errors has no sense for the error and log counters printLong(MetricType.COUNTER, sanitizedName + "_errors_count", "javamelody counter", errors); } if (duration >= 0) { // duration is negative and has no sense for the log counter printLong(MetricType.COUNTER, sanitizedName + "_duration_millis", "javamelody counter", duration); } } }
[ "private", "void", "reportOnCollector", "(", ")", "{", "for", "(", "final", "Counter", "counter", ":", "collector", ".", "getCounters", "(", ")", ")", "{", "if", "(", "!", "counter", ".", "isDisplayed", "(", ")", ")", "{", "continue", ";", "}", "final", "List", "<", "CounterRequest", ">", "requests", "=", "counter", ".", "getRequests", "(", ")", ";", "long", "hits", "=", "0", ";", "long", "duration", "=", "0", ";", "long", "errors", "=", "0", ";", "for", "(", "final", "CounterRequest", "cr", ":", "requests", ")", "{", "hits", "+=", "cr", ".", "getHits", "(", ")", ";", "duration", "+=", "cr", ".", "getDurationsSum", "(", ")", ";", "errors", "+=", "cr", ".", "getSystemErrors", "(", ")", ";", "}", "final", "String", "sanitizedName", "=", "sanitizeName", "(", "counter", ".", "getName", "(", ")", ")", ";", "printLong", "(", "MetricType", ".", "COUNTER", ",", "sanitizedName", "+", "\"_hits_count\"", ",", "\"javamelody counter\"", ",", "hits", ")", ";", "if", "(", "!", "counter", ".", "isErrorCounter", "(", ")", "||", "counter", ".", "isJobCounter", "(", ")", ")", "{", "// errors has no sense for the error and log counters\r", "printLong", "(", "MetricType", ".", "COUNTER", ",", "sanitizedName", "+", "\"_errors_count\"", ",", "\"javamelody counter\"", ",", "errors", ")", ";", "}", "if", "(", "duration", ">=", "0", ")", "{", "// duration is negative and has no sense for the log counter\r", "printLong", "(", "MetricType", ".", "COUNTER", ",", "sanitizedName", "+", "\"_duration_millis\"", ",", "\"javamelody counter\"", ",", "duration", ")", ";", "}", "}", "}" ]
Reports on hits, errors, and duration sum for all counters in the collector. Bypasses the {@link JRobin#getLastValue()} methods to provide real-time counters as well as improving performance from bypassing JRobin reads in the getLastValue() method.
[ "Reports", "on", "hits", "errors", "and", "duration", "sum", "for", "all", "counters", "in", "the", "collector", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java#L353-L382
19,320
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java
PrometheusController.reportOnLastValues
private void reportOnLastValues() throws IOException { Collection<JRobin> jrobins = collector.getDisplayedCounterJRobins(); for (final JRobin jrobin : jrobins) { printDouble(MetricType.GAUGE, "last_value_" + camelToSnake(jrobin.getName()), "javamelody value per minute", jrobin.getLastValue()); } jrobins = collector.getDisplayedOtherJRobins(); for (final JRobin jrobin : jrobins) { printDouble(MetricType.GAUGE, "last_value_" + camelToSnake(jrobin.getName()), "javamelody value per minute", jrobin.getLastValue()); } }
java
private void reportOnLastValues() throws IOException { Collection<JRobin> jrobins = collector.getDisplayedCounterJRobins(); for (final JRobin jrobin : jrobins) { printDouble(MetricType.GAUGE, "last_value_" + camelToSnake(jrobin.getName()), "javamelody value per minute", jrobin.getLastValue()); } jrobins = collector.getDisplayedOtherJRobins(); for (final JRobin jrobin : jrobins) { printDouble(MetricType.GAUGE, "last_value_" + camelToSnake(jrobin.getName()), "javamelody value per minute", jrobin.getLastValue()); } }
[ "private", "void", "reportOnLastValues", "(", ")", "throws", "IOException", "{", "Collection", "<", "JRobin", ">", "jrobins", "=", "collector", ".", "getDisplayedCounterJRobins", "(", ")", ";", "for", "(", "final", "JRobin", "jrobin", ":", "jrobins", ")", "{", "printDouble", "(", "MetricType", ".", "GAUGE", ",", "\"last_value_\"", "+", "camelToSnake", "(", "jrobin", ".", "getName", "(", ")", ")", ",", "\"javamelody value per minute\"", ",", "jrobin", ".", "getLastValue", "(", ")", ")", ";", "}", "jrobins", "=", "collector", ".", "getDisplayedOtherJRobins", "(", ")", ";", "for", "(", "final", "JRobin", "jrobin", ":", "jrobins", ")", "{", "printDouble", "(", "MetricType", ".", "GAUGE", ",", "\"last_value_\"", "+", "camelToSnake", "(", "jrobin", ".", "getName", "(", ")", ")", ",", "\"javamelody value per minute\"", ",", "jrobin", ".", "getLastValue", "(", ")", ")", ";", "}", "}" ]
Includes the traditional 'graph' fields from the 'lastValue' API. These fields are summary fields aggregated over `javamelody.resolutions-seconds` (default 60), which is normally an odd thing to pass to Prometheus. Most (all?) of these can be calculated inside Prometheus from the Collector stats. Note: This lookup seems to take the longest execution time -- 5-10ms per request due to JRobin reads. Disabled by default. To enable set the 'prometheus-include-last-value' property to 'true'. @throws IOException e
[ "Includes", "the", "traditional", "graph", "fields", "from", "the", "lastValue", "API", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java#L397-L409
19,321
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java
PrometheusController.camelToSnake
private static String camelToSnake(String camel) { return CAMEL_TO_SNAKE_PATTERN.matcher(camel).replaceAll("$1_$2").toLowerCase(Locale.US); }
java
private static String camelToSnake(String camel) { return CAMEL_TO_SNAKE_PATTERN.matcher(camel).replaceAll("$1_$2").toLowerCase(Locale.US); }
[ "private", "static", "String", "camelToSnake", "(", "String", "camel", ")", "{", "return", "CAMEL_TO_SNAKE_PATTERN", ".", "matcher", "(", "camel", ")", ".", "replaceAll", "(", "\"$1_$2\"", ")", ".", "toLowerCase", "(", "Locale", ".", "US", ")", ";", "}" ]
Converts a camelCase or CamelCase string to camel_case @param camel String @return String
[ "Converts", "a", "camelCase", "or", "CamelCase", "string", "to", "camel_case" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java#L516-L518
19,322
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java
PrometheusController.sanitizeName
private static String sanitizeName(String name) { final String lowerCaseName = name.toLowerCase(Locale.US); final String separatorReplacedName = SANITIZE_TO_UNDERSCORE_PATTERN.matcher(lowerCaseName) .replaceAll(UNDERSCORE); return SANITIZE_REMOVE_PATTERN.matcher(separatorReplacedName).replaceAll(EMPTY_STRING); }
java
private static String sanitizeName(String name) { final String lowerCaseName = name.toLowerCase(Locale.US); final String separatorReplacedName = SANITIZE_TO_UNDERSCORE_PATTERN.matcher(lowerCaseName) .replaceAll(UNDERSCORE); return SANITIZE_REMOVE_PATTERN.matcher(separatorReplacedName).replaceAll(EMPTY_STRING); }
[ "private", "static", "String", "sanitizeName", "(", "String", "name", ")", "{", "final", "String", "lowerCaseName", "=", "name", ".", "toLowerCase", "(", "Locale", ".", "US", ")", ";", "final", "String", "separatorReplacedName", "=", "SANITIZE_TO_UNDERSCORE_PATTERN", ".", "matcher", "(", "lowerCaseName", ")", ".", "replaceAll", "(", "UNDERSCORE", ")", ";", "return", "SANITIZE_REMOVE_PATTERN", ".", "matcher", "(", "separatorReplacedName", ")", ".", "replaceAll", "(", "EMPTY_STRING", ")", ";", "}" ]
converts to lowercase, replaces common separators with underscores, and strips all remaining non-alpha-numeric characters. @param name String @return String
[ "converts", "to", "lowercase", "replaces", "common", "separators", "with", "underscores", "and", "strips", "all", "remaining", "non", "-", "alpha", "-", "numeric", "characters", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java#L525-L530
19,323
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java
PrometheusController.printLong
private void printLong(MetricType metricType, String name, String description, long value) { printHeader(metricType, name, description); printLongWithFields(name, null, value); }
java
private void printLong(MetricType metricType, String name, String description, long value) { printHeader(metricType, name, description); printLongWithFields(name, null, value); }
[ "private", "void", "printLong", "(", "MetricType", "metricType", ",", "String", "name", ",", "String", "description", ",", "long", "value", ")", "{", "printHeader", "(", "metricType", ",", "name", ",", "description", ")", ";", "printLongWithFields", "(", "name", ",", "null", ",", "value", ")", ";", "}" ]
prints a long metric value, including HELP and TYPE rows
[ "prints", "a", "long", "metric", "value", "including", "HELP", "and", "TYPE", "rows" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java#L533-L536
19,324
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java
PrometheusController.printDouble
private void printDouble(MetricType metricType, String name, String description, double value) { printHeader(metricType, name, description); printDoubleWithFields(name, null, value); }
java
private void printDouble(MetricType metricType, String name, String description, double value) { printHeader(metricType, name, description); printDoubleWithFields(name, null, value); }
[ "private", "void", "printDouble", "(", "MetricType", "metricType", ",", "String", "name", ",", "String", "description", ",", "double", "value", ")", "{", "printHeader", "(", "metricType", ",", "name", ",", "description", ")", ";", "printDoubleWithFields", "(", "name", ",", "null", ",", "value", ")", ";", "}" ]
prints a double metric value, including HELP and TYPE rows
[ "prints", "a", "double", "metric", "value", "including", "HELP", "and", "TYPE", "rows" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java#L539-L542
19,325
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java
PrometheusController.printLongWithFields
private void printLongWithFields(String name, String fields, long value) { print(METRIC_PREFIX); print(name); if (fields != null) { print(fields); } print(' '); println(String.valueOf(value)); }
java
private void printLongWithFields(String name, String fields, long value) { print(METRIC_PREFIX); print(name); if (fields != null) { print(fields); } print(' '); println(String.valueOf(value)); }
[ "private", "void", "printLongWithFields", "(", "String", "name", ",", "String", "fields", ",", "long", "value", ")", "{", "print", "(", "METRIC_PREFIX", ")", ";", "print", "(", "name", ")", ";", "if", "(", "fields", "!=", "null", ")", "{", "print", "(", "fields", ")", ";", "}", "print", "(", "'", "'", ")", ";", "println", "(", "String", ".", "valueOf", "(", "value", ")", ")", ";", "}" ]
prints a long metric value with optional fields
[ "prints", "a", "long", "metric", "value", "with", "optional", "fields" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java#L545-L553
19,326
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java
PrometheusController.printDoubleWithFields
private void printDoubleWithFields(String name, String fields, double value) { print(METRIC_PREFIX); print(name); if (fields != null) { print(fields); } print(' '); println(decimalFormat.format(value)); }
java
private void printDoubleWithFields(String name, String fields, double value) { print(METRIC_PREFIX); print(name); if (fields != null) { print(fields); } print(' '); println(decimalFormat.format(value)); }
[ "private", "void", "printDoubleWithFields", "(", "String", "name", ",", "String", "fields", ",", "double", "value", ")", "{", "print", "(", "METRIC_PREFIX", ")", ";", "print", "(", "name", ")", ";", "if", "(", "fields", "!=", "null", ")", "{", "print", "(", "fields", ")", ";", "}", "print", "(", "'", "'", ")", ";", "println", "(", "decimalFormat", ".", "format", "(", "value", ")", ")", ";", "}" ]
prints a double metric value with optional fields
[ "prints", "a", "double", "metric", "value", "with", "optional", "fields" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java#L556-L564
19,327
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java
PrometheusController.printHeader
private void printHeader(MetricType metricType, String name, String description) { print("# HELP "); print(METRIC_PREFIX); print(name); print(' '); println(description); print("# TYPE "); print(METRIC_PREFIX); print(name); print(' '); println(metricType.getCode()); }
java
private void printHeader(MetricType metricType, String name, String description) { print("# HELP "); print(METRIC_PREFIX); print(name); print(' '); println(description); print("# TYPE "); print(METRIC_PREFIX); print(name); print(' '); println(metricType.getCode()); }
[ "private", "void", "printHeader", "(", "MetricType", "metricType", ",", "String", "name", ",", "String", "description", ")", "{", "print", "(", "\"# HELP \"", ")", ";", "print", "(", "METRIC_PREFIX", ")", ";", "print", "(", "name", ")", ";", "print", "(", "'", "'", ")", ";", "println", "(", "description", ")", ";", "print", "(", "\"# TYPE \"", ")", ";", "print", "(", "METRIC_PREFIX", ")", ";", "print", "(", "name", ")", ";", "print", "(", "'", "'", ")", ";", "println", "(", "metricType", ".", "getCode", "(", ")", ")", ";", "}" ]
prints the HELP and TYPE rows
[ "prints", "the", "HELP", "and", "TYPE", "rows" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/PrometheusController.java#L567-L579
19,328
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/FilterContext.java
FilterContext.unregisterJmxExpose
private void unregisterJmxExpose() { if (jmxNames.isEmpty()) { return; } try { final MBeanServer platformMBeanServer = MBeans.getPlatformMBeanServer(); for (final ObjectName name : jmxNames) { platformMBeanServer.unregisterMBean(name); } } catch (final JMException e) { LOG.warn("failed to unregister JMX beans", e); } }
java
private void unregisterJmxExpose() { if (jmxNames.isEmpty()) { return; } try { final MBeanServer platformMBeanServer = MBeans.getPlatformMBeanServer(); for (final ObjectName name : jmxNames) { platformMBeanServer.unregisterMBean(name); } } catch (final JMException e) { LOG.warn("failed to unregister JMX beans", e); } }
[ "private", "void", "unregisterJmxExpose", "(", ")", "{", "if", "(", "jmxNames", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "try", "{", "final", "MBeanServer", "platformMBeanServer", "=", "MBeans", ".", "getPlatformMBeanServer", "(", ")", ";", "for", "(", "final", "ObjectName", "name", ":", "jmxNames", ")", "{", "platformMBeanServer", ".", "unregisterMBean", "(", "name", ")", ";", "}", "}", "catch", "(", "final", "JMException", "e", ")", "{", "LOG", ".", "warn", "(", "\"failed to unregister JMX beans\"", ",", "e", ")", ";", "}", "}" ]
Unregisters CounterRequestMXBean beans.
[ "Unregisters", "CounterRequestMXBean", "beans", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/FilterContext.java#L512-L524
19,329
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/AdvancedPageNumberEvents.java
AdvancedPageNumberEvents.onGenericTag
@Override public void onGenericTag(final PdfWriter writer, final Document document, final Rectangle rect, final String text) { // rien ici }
java
@Override public void onGenericTag(final PdfWriter writer, final Document document, final Rectangle rect, final String text) { // rien ici }
[ "@", "Override", "public", "void", "onGenericTag", "(", "final", "PdfWriter", "writer", ",", "final", "Document", "document", ",", "final", "Rectangle", "rect", ",", "final", "String", "text", ")", "{", "// rien ici\r", "}" ]
we override the onGenericTag method. @param writer PdfWriter @param document Document @param rect Rectangle @param text String
[ "we", "override", "the", "onGenericTag", "method", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/AdvancedPageNumberEvents.java#L59-L63
19,330
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/AdvancedPageNumberEvents.java
AdvancedPageNumberEvents.onOpenDocument
@Override public void onOpenDocument(final PdfWriter writer, final Document document) { try { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb = writer.getDirectContent(); template = cb.createTemplate(50, 50); } catch (final DocumentException de) { throw new IllegalStateException(de); } catch (final IOException ioe) { throw new IllegalStateException(ioe); } }
java
@Override public void onOpenDocument(final PdfWriter writer, final Document document) { try { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb = writer.getDirectContent(); template = cb.createTemplate(50, 50); } catch (final DocumentException de) { throw new IllegalStateException(de); } catch (final IOException ioe) { throw new IllegalStateException(ioe); } }
[ "@", "Override", "public", "void", "onOpenDocument", "(", "final", "PdfWriter", "writer", ",", "final", "Document", "document", ")", "{", "try", "{", "bf", "=", "BaseFont", ".", "createFont", "(", "BaseFont", ".", "HELVETICA", ",", "BaseFont", ".", "CP1252", ",", "BaseFont", ".", "NOT_EMBEDDED", ")", ";", "cb", "=", "writer", ".", "getDirectContent", "(", ")", ";", "template", "=", "cb", ".", "createTemplate", "(", "50", ",", "50", ")", ";", "}", "catch", "(", "final", "DocumentException", "de", ")", "{", "throw", "new", "IllegalStateException", "(", "de", ")", ";", "}", "catch", "(", "final", "IOException", "ioe", ")", "{", "throw", "new", "IllegalStateException", "(", "ioe", ")", ";", "}", "}" ]
we override the onOpenDocument method. @param writer PdfWriter @param document Document
[ "we", "override", "the", "onOpenDocument", "method", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/AdvancedPageNumberEvents.java#L73-L84
19,331
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/AdvancedPageNumberEvents.java
AdvancedPageNumberEvents.onEndPage
@Override public void onEndPage(final PdfWriter writer, final Document document) { final int pageN = writer.getPageNumber(); final String text = pageN + " / "; final float len = bf.getWidthPoint(text, 8); cb.beginText(); cb.setFontAndSize(bf, 8); final float width = document.getPageSize().getWidth(); cb.setTextMatrix(width / 2, 30); cb.showText(text); cb.endText(); cb.addTemplate(template, width / 2 + len, 30); }
java
@Override public void onEndPage(final PdfWriter writer, final Document document) { final int pageN = writer.getPageNumber(); final String text = pageN + " / "; final float len = bf.getWidthPoint(text, 8); cb.beginText(); cb.setFontAndSize(bf, 8); final float width = document.getPageSize().getWidth(); cb.setTextMatrix(width / 2, 30); cb.showText(text); cb.endText(); cb.addTemplate(template, width / 2 + len, 30); }
[ "@", "Override", "public", "void", "onEndPage", "(", "final", "PdfWriter", "writer", ",", "final", "Document", "document", ")", "{", "final", "int", "pageN", "=", "writer", ".", "getPageNumber", "(", ")", ";", "final", "String", "text", "=", "pageN", "+", "\" / \"", ";", "final", "float", "len", "=", "bf", ".", "getWidthPoint", "(", "text", ",", "8", ")", ";", "cb", ".", "beginText", "(", ")", ";", "cb", ".", "setFontAndSize", "(", "bf", ",", "8", ")", ";", "final", "float", "width", "=", "document", ".", "getPageSize", "(", ")", ".", "getWidth", "(", ")", ";", "cb", ".", "setTextMatrix", "(", "width", "/", "2", ",", "30", ")", ";", "cb", ".", "showText", "(", "text", ")", ";", "cb", ".", "endText", "(", ")", ";", "cb", ".", "addTemplate", "(", "template", ",", "width", "/", "2", "+", "len", ",", "30", ")", ";", "}" ]
we override the onEndPage method. @param writer PdfWriter @param document Document
[ "we", "override", "the", "onEndPage", "method", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/AdvancedPageNumberEvents.java#L112-L124
19,332
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/AdvancedPageNumberEvents.java
AdvancedPageNumberEvents.onCloseDocument
@Override public void onCloseDocument(final PdfWriter writer, final Document document) { template.beginText(); template.setFontAndSize(bf, 8); template.showText(String.valueOf(writer.getPageNumber() - 1)); template.endText(); }
java
@Override public void onCloseDocument(final PdfWriter writer, final Document document) { template.beginText(); template.setFontAndSize(bf, 8); template.showText(String.valueOf(writer.getPageNumber() - 1)); template.endText(); }
[ "@", "Override", "public", "void", "onCloseDocument", "(", "final", "PdfWriter", "writer", ",", "final", "Document", "document", ")", "{", "template", ".", "beginText", "(", ")", ";", "template", ".", "setFontAndSize", "(", "bf", ",", "8", ")", ";", "template", ".", "showText", "(", "String", ".", "valueOf", "(", "writer", ".", "getPageNumber", "(", ")", "-", "1", ")", ")", ";", "template", ".", "endText", "(", ")", ";", "}" ]
we override the onCloseDocument method. @param writer PdfWriter @param document Document
[ "we", "override", "the", "onCloseDocument", "method", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/AdvancedPageNumberEvents.java#L134-L140
19,333
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/JRobin.java
JRobin.initBackendFactory
public static void initBackendFactory(Timer timer) throws IOException { RrdNioBackend.setFileSyncTimer(timer); try { if (!RrdBackendFactory.getDefaultFactory().getFactoryName() .equals(RrdNioBackendFactory.FACTORY_NAME)) { RrdBackendFactory.registerAndSetAsDefaultFactory(new RrdNioBackendFactory()); } } catch (final RrdException e) { throw createIOException(e); } }
java
public static void initBackendFactory(Timer timer) throws IOException { RrdNioBackend.setFileSyncTimer(timer); try { if (!RrdBackendFactory.getDefaultFactory().getFactoryName() .equals(RrdNioBackendFactory.FACTORY_NAME)) { RrdBackendFactory.registerAndSetAsDefaultFactory(new RrdNioBackendFactory()); } } catch (final RrdException e) { throw createIOException(e); } }
[ "public", "static", "void", "initBackendFactory", "(", "Timer", "timer", ")", "throws", "IOException", "{", "RrdNioBackend", ".", "setFileSyncTimer", "(", "timer", ")", ";", "try", "{", "if", "(", "!", "RrdBackendFactory", ".", "getDefaultFactory", "(", ")", ".", "getFactoryName", "(", ")", ".", "equals", "(", "RrdNioBackendFactory", ".", "FACTORY_NAME", ")", ")", "{", "RrdBackendFactory", ".", "registerAndSetAsDefaultFactory", "(", "new", "RrdNioBackendFactory", "(", ")", ")", ";", "}", "}", "catch", "(", "final", "RrdException", "e", ")", "{", "throw", "createIOException", "(", "e", ")", ";", "}", "}" ]
JavaMelody uses a custom RrdNioBackendFactory, in order to use its own and cancelable file sync timer. @param timer Timer @throws IOException e
[ "JavaMelody", "uses", "a", "custom", "RrdNioBackendFactory", "in", "order", "to", "use", "its", "own", "and", "cancelable", "file", "sync", "timer", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/JRobin.java#L138-L149
19,334
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MCsvWriter.java
MCsvWriter.formatCsv
protected String formatCsv(final String text, final char csvSeparator) { String result = text; if (result.indexOf('\n') != -1) { // le retour chariot fonctionne dans les dernières versions d'excel entre des doubles quotes // mais il ne fonctionne pas dans OpenOffice 1.1.2 result = result.replace('\n', ' '); } int index = result.indexOf('"'); while (index != -1) { // on double les double-quote pour csv (non performant mais rare) result = new StringBuilder(result).insert(index, '"').toString(); index = result.indexOf('"', index + 2); } if (text.indexOf(csvSeparator) != -1 || text.indexOf('"') != -1) { final String tmp = '"' + result + '"'; result = tmp; } return result; }
java
protected String formatCsv(final String text, final char csvSeparator) { String result = text; if (result.indexOf('\n') != -1) { // le retour chariot fonctionne dans les dernières versions d'excel entre des doubles quotes // mais il ne fonctionne pas dans OpenOffice 1.1.2 result = result.replace('\n', ' '); } int index = result.indexOf('"'); while (index != -1) { // on double les double-quote pour csv (non performant mais rare) result = new StringBuilder(result).insert(index, '"').toString(); index = result.indexOf('"', index + 2); } if (text.indexOf(csvSeparator) != -1 || text.indexOf('"') != -1) { final String tmp = '"' + result + '"'; result = tmp; } return result; }
[ "protected", "String", "formatCsv", "(", "final", "String", "text", ",", "final", "char", "csvSeparator", ")", "{", "String", "result", "=", "text", ";", "if", "(", "result", ".", "indexOf", "(", "'", "'", ")", "!=", "-", "1", ")", "{", "// le retour chariot fonctionne dans les dernières versions d'excel entre des doubles quotes\r", "// mais il ne fonctionne pas dans OpenOffice 1.1.2\r", "result", "=", "result", ".", "replace", "(", "'", "'", ",", "'", "'", ")", ";", "}", "int", "index", "=", "result", ".", "indexOf", "(", "'", "'", ")", ";", "while", "(", "index", "!=", "-", "1", ")", "{", "// on double les double-quote pour csv (non performant mais rare)\r", "result", "=", "new", "StringBuilder", "(", "result", ")", ".", "insert", "(", "index", ",", "'", "'", ")", ".", "toString", "(", ")", ";", "index", "=", "result", ".", "indexOf", "(", "'", "'", ",", "index", "+", "2", ")", ";", "}", "if", "(", "text", ".", "indexOf", "(", "csvSeparator", ")", "!=", "-", "1", "||", "text", ".", "indexOf", "(", "'", "'", ")", "!=", "-", "1", ")", "{", "final", "String", "tmp", "=", "'", "'", "+", "result", "+", "'", "'", ";", "result", "=", "tmp", ";", "}", "return", "result", ";", "}" ]
Encode un texte pour l'export au format csv ou csv local. @return String @param text String @param csvSeparator char
[ "Encode", "un", "texte", "pour", "l", "export", "au", "format", "csv", "ou", "csv", "local", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MCsvWriter.java#L84-L102
19,335
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MCsvWriter.java
MCsvWriter.writeCsvHeader
protected void writeCsvHeader(final JTable table, final Writer out, final char csvSeparator) throws IOException { // récupération des informations utiles final int columnCount = table.getColumnModel().getColumnCount(); final String eol = System.getProperty("line.separator"); if (table.getName() != null) { String title = formatCsv(table.getName(), csvSeparator); if (title.startsWith("ID")) { final String tmp = '"' + title + '"'; title = tmp; } out.write(title); out.write(eol); } // titres des colonnes String text; for (int i = 0; i < columnCount; i++) { text = String.valueOf(table.getColumnModel().getColumn(i).getHeaderValue()); text = formatCsv(text, csvSeparator); if (i == 0 && text.startsWith("ID")) { out.write('"' + text + '"'); // si commence par ID, Excel pense que c'est un sylk ! } else { out.write(text); } if (i < columnCount - 1) { out.write(csvSeparator); } } out.write(eol); }
java
protected void writeCsvHeader(final JTable table, final Writer out, final char csvSeparator) throws IOException { // récupération des informations utiles final int columnCount = table.getColumnModel().getColumnCount(); final String eol = System.getProperty("line.separator"); if (table.getName() != null) { String title = formatCsv(table.getName(), csvSeparator); if (title.startsWith("ID")) { final String tmp = '"' + title + '"'; title = tmp; } out.write(title); out.write(eol); } // titres des colonnes String text; for (int i = 0; i < columnCount; i++) { text = String.valueOf(table.getColumnModel().getColumn(i).getHeaderValue()); text = formatCsv(text, csvSeparator); if (i == 0 && text.startsWith("ID")) { out.write('"' + text + '"'); // si commence par ID, Excel pense que c'est un sylk ! } else { out.write(text); } if (i < columnCount - 1) { out.write(csvSeparator); } } out.write(eol); }
[ "protected", "void", "writeCsvHeader", "(", "final", "JTable", "table", ",", "final", "Writer", "out", ",", "final", "char", "csvSeparator", ")", "throws", "IOException", "{", "// récupération des informations utiles\r", "final", "int", "columnCount", "=", "table", ".", "getColumnModel", "(", ")", ".", "getColumnCount", "(", ")", ";", "final", "String", "eol", "=", "System", ".", "getProperty", "(", "\"line.separator\"", ")", ";", "if", "(", "table", ".", "getName", "(", ")", "!=", "null", ")", "{", "String", "title", "=", "formatCsv", "(", "table", ".", "getName", "(", ")", ",", "csvSeparator", ")", ";", "if", "(", "title", ".", "startsWith", "(", "\"ID\"", ")", ")", "{", "final", "String", "tmp", "=", "'", "'", "+", "title", "+", "'", "'", ";", "title", "=", "tmp", ";", "}", "out", ".", "write", "(", "title", ")", ";", "out", ".", "write", "(", "eol", ")", ";", "}", "// titres des colonnes\r", "String", "text", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "columnCount", ";", "i", "++", ")", "{", "text", "=", "String", ".", "valueOf", "(", "table", ".", "getColumnModel", "(", ")", ".", "getColumn", "(", "i", ")", ".", "getHeaderValue", "(", ")", ")", ";", "text", "=", "formatCsv", "(", "text", ",", "csvSeparator", ")", ";", "if", "(", "i", "==", "0", "&&", "text", ".", "startsWith", "(", "\"ID\"", ")", ")", "{", "out", ".", "write", "(", "'", "'", "+", "text", "+", "'", "'", ")", ";", "// si commence par ID, Excel pense que c'est un sylk !\r", "}", "else", "{", "out", ".", "write", "(", "text", ")", ";", "}", "if", "(", "i", "<", "columnCount", "-", "1", ")", "{", "out", ".", "write", "(", "csvSeparator", ")", ";", "}", "}", "out", ".", "write", "(", "eol", ")", ";", "}" ]
Exporte les headers csv d'une JTable.. @param table JTable @param out Writer @param csvSeparator char @throws IOException Erreur disque
[ "Exporte", "les", "headers", "csv", "d", "une", "JTable", ".." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MCsvWriter.java#L190-L220
19,336
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/FilterServletResponseWrapper.java
FilterServletResponseWrapper.close
public void close() throws IOException { if (writer != null) { writer.close(); } else if (stream != null) { stream.close(); } }
java
public void close() throws IOException { if (writer != null) { writer.close(); } else if (stream != null) { stream.close(); } }
[ "public", "void", "close", "(", ")", "throws", "IOException", "{", "if", "(", "writer", "!=", "null", ")", "{", "writer", ".", "close", "(", ")", ";", "}", "else", "if", "(", "stream", "!=", "null", ")", "{", "stream", ".", "close", "(", ")", ";", "}", "}" ]
Ferme le flux. @throws IOException e
[ "Ferme", "le", "flux", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/FilterServletResponseWrapper.java#L166-L172
19,337
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MRtfWriter.java
MRtfWriter.createWriter
@Override protected DocWriter createWriter(final MBasicTable table, final Document document, final OutputStream out) { final RtfWriter2 writer = RtfWriter2.getInstance(document, out); // title final String title = buildTitle(table); if (title != null) { final HeaderFooter header = new RtfHeaderFooter(new Paragraph(title)); header.setAlignment(Element.ALIGN_LEFT); header.setBorder(Rectangle.NO_BORDER); document.setHeader(header); document.addTitle(title); } // advanced page numbers : x/y final Paragraph footerParagraph = new Paragraph(); final Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL); footerParagraph.add(new RtfPageNumber(font)); footerParagraph.add(new Phrase(" / ", font)); footerParagraph.add(new RtfTotalPageNumber(font)); footerParagraph.setAlignment(Element.ALIGN_CENTER); final HeaderFooter footer = new RtfHeaderFooter(footerParagraph); footer.setBorder(Rectangle.TOP); document.setFooter(footer); return writer; }
java
@Override protected DocWriter createWriter(final MBasicTable table, final Document document, final OutputStream out) { final RtfWriter2 writer = RtfWriter2.getInstance(document, out); // title final String title = buildTitle(table); if (title != null) { final HeaderFooter header = new RtfHeaderFooter(new Paragraph(title)); header.setAlignment(Element.ALIGN_LEFT); header.setBorder(Rectangle.NO_BORDER); document.setHeader(header); document.addTitle(title); } // advanced page numbers : x/y final Paragraph footerParagraph = new Paragraph(); final Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.NORMAL); footerParagraph.add(new RtfPageNumber(font)); footerParagraph.add(new Phrase(" / ", font)); footerParagraph.add(new RtfTotalPageNumber(font)); footerParagraph.setAlignment(Element.ALIGN_CENTER); final HeaderFooter footer = new RtfHeaderFooter(footerParagraph); footer.setBorder(Rectangle.TOP); document.setFooter(footer); return writer; }
[ "@", "Override", "protected", "DocWriter", "createWriter", "(", "final", "MBasicTable", "table", ",", "final", "Document", "document", ",", "final", "OutputStream", "out", ")", "{", "final", "RtfWriter2", "writer", "=", "RtfWriter2", ".", "getInstance", "(", "document", ",", "out", ")", ";", "// title\r", "final", "String", "title", "=", "buildTitle", "(", "table", ")", ";", "if", "(", "title", "!=", "null", ")", "{", "final", "HeaderFooter", "header", "=", "new", "RtfHeaderFooter", "(", "new", "Paragraph", "(", "title", ")", ")", ";", "header", ".", "setAlignment", "(", "Element", ".", "ALIGN_LEFT", ")", ";", "header", ".", "setBorder", "(", "Rectangle", ".", "NO_BORDER", ")", ";", "document", ".", "setHeader", "(", "header", ")", ";", "document", ".", "addTitle", "(", "title", ")", ";", "}", "// advanced page numbers : x/y\r", "final", "Paragraph", "footerParagraph", "=", "new", "Paragraph", "(", ")", ";", "final", "Font", "font", "=", "FontFactory", ".", "getFont", "(", "FontFactory", ".", "TIMES_ROMAN", ",", "12", ",", "Font", ".", "NORMAL", ")", ";", "footerParagraph", ".", "add", "(", "new", "RtfPageNumber", "(", "font", ")", ")", ";", "footerParagraph", ".", "add", "(", "new", "Phrase", "(", "\" / \"", ",", "font", ")", ")", ";", "footerParagraph", ".", "add", "(", "new", "RtfTotalPageNumber", "(", "font", ")", ")", ";", "footerParagraph", ".", "setAlignment", "(", "Element", ".", "ALIGN_CENTER", ")", ";", "final", "HeaderFooter", "footer", "=", "new", "RtfHeaderFooter", "(", "footerParagraph", ")", ";", "footer", ".", "setBorder", "(", "Rectangle", ".", "TOP", ")", ";", "document", ".", "setFooter", "(", "footer", ")", ";", "return", "writer", ";", "}" ]
We create a writer that listens to the document and directs a RTF-stream to out @param table MBasicTable @param document Document @param out OutputStream @return DocWriter
[ "We", "create", "a", "writer", "that", "listens", "to", "the", "document", "and", "directs", "a", "RTF", "-", "stream", "to", "out" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MRtfWriter.java#L124-L151
19,338
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/MonitoringSpringInterceptor.java
MonitoringSpringInterceptor.invoke
@Override public Object invoke(MethodInvocation invocation) throws Throwable { // cette méthode est appelée par spring aop if (DISABLED || !SPRING_COUNTER.isDisplayed()) { return invocation.proceed(); } // nom identifiant la requête final String requestName = getRequestName(invocation); boolean systemError = false; try { SPRING_COUNTER.bindContextIncludingCpu(requestName); return invocation.proceed(); } catch (final Error e) { // on catche Error pour avoir les erreurs systèmes // mais pas Exception qui sont fonctionnelles en général systemError = true; throw e; } finally { // on enregistre la requête dans les statistiques SPRING_COUNTER.addRequestForCurrentContext(systemError); } }
java
@Override public Object invoke(MethodInvocation invocation) throws Throwable { // cette méthode est appelée par spring aop if (DISABLED || !SPRING_COUNTER.isDisplayed()) { return invocation.proceed(); } // nom identifiant la requête final String requestName = getRequestName(invocation); boolean systemError = false; try { SPRING_COUNTER.bindContextIncludingCpu(requestName); return invocation.proceed(); } catch (final Error e) { // on catche Error pour avoir les erreurs systèmes // mais pas Exception qui sont fonctionnelles en général systemError = true; throw e; } finally { // on enregistre la requête dans les statistiques SPRING_COUNTER.addRequestForCurrentContext(systemError); } }
[ "@", "Override", "public", "Object", "invoke", "(", "MethodInvocation", "invocation", ")", "throws", "Throwable", "{", "// cette méthode est appelée par spring aop\r", "if", "(", "DISABLED", "||", "!", "SPRING_COUNTER", ".", "isDisplayed", "(", ")", ")", "{", "return", "invocation", ".", "proceed", "(", ")", ";", "}", "// nom identifiant la requête\r", "final", "String", "requestName", "=", "getRequestName", "(", "invocation", ")", ";", "boolean", "systemError", "=", "false", ";", "try", "{", "SPRING_COUNTER", ".", "bindContextIncludingCpu", "(", "requestName", ")", ";", "return", "invocation", ".", "proceed", "(", ")", ";", "}", "catch", "(", "final", "Error", "e", ")", "{", "// on catche Error pour avoir les erreurs systèmes\r", "// mais pas Exception qui sont fonctionnelles en général\r", "systemError", "=", "true", ";", "throw", "e", ";", "}", "finally", "{", "// on enregistre la requête dans les statistiques\r", "SPRING_COUNTER", ".", "addRequestForCurrentContext", "(", "systemError", ")", ";", "}", "}" ]
Performs method invocation. @param invocation method invocation @return return object from the method @throws Throwable anything thrown by the method
[ "Performs", "method", "invocation", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/MonitoringSpringInterceptor.java#L64-L86
19,339
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/MonitoringProxy.java
MonitoringProxy.invokeTarget
public static Object invokeTarget(Object target, Method method, Object[] args, final String requestName) throws IllegalAccessException, InvocationTargetException { boolean systemError = false; try { SERVICES_COUNTER.bindContextIncludingCpu(requestName); return method.invoke(target, args); } catch (final InvocationTargetException e) { if (e.getCause() instanceof Error) { // on catche Error pour avoir les erreurs systèmes // mais pas Exception qui sont fonctionnelles en général systemError = true; } throw e; } finally { // on enregistre la requête dans les statistiques SERVICES_COUNTER.addRequestForCurrentContext(systemError); } }
java
public static Object invokeTarget(Object target, Method method, Object[] args, final String requestName) throws IllegalAccessException, InvocationTargetException { boolean systemError = false; try { SERVICES_COUNTER.bindContextIncludingCpu(requestName); return method.invoke(target, args); } catch (final InvocationTargetException e) { if (e.getCause() instanceof Error) { // on catche Error pour avoir les erreurs systèmes // mais pas Exception qui sont fonctionnelles en général systemError = true; } throw e; } finally { // on enregistre la requête dans les statistiques SERVICES_COUNTER.addRequestForCurrentContext(systemError); } }
[ "public", "static", "Object", "invokeTarget", "(", "Object", "target", ",", "Method", "method", ",", "Object", "[", "]", "args", ",", "final", "String", "requestName", ")", "throws", "IllegalAccessException", ",", "InvocationTargetException", "{", "boolean", "systemError", "=", "false", ";", "try", "{", "SERVICES_COUNTER", ".", "bindContextIncludingCpu", "(", "requestName", ")", ";", "return", "method", ".", "invoke", "(", "target", ",", "args", ")", ";", "}", "catch", "(", "final", "InvocationTargetException", "e", ")", "{", "if", "(", "e", ".", "getCause", "(", ")", "instanceof", "Error", ")", "{", "// on catche Error pour avoir les erreurs systèmes\r", "// mais pas Exception qui sont fonctionnelles en général\r", "systemError", "=", "true", ";", "}", "throw", "e", ";", "}", "finally", "{", "// on enregistre la requête dans les statistiques\r", "SERVICES_COUNTER", ".", "addRequestForCurrentContext", "(", "systemError", ")", ";", "}", "}" ]
Invoke target. @param target Instance to call @param method Method to call @param args Method arguments @param requestName Request name to display @return Result @throws IllegalAccessException e @throws InvocationTargetException e
[ "Invoke", "target", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/MonitoringProxy.java#L177-L194
19,340
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/LabradorRetriever.java
LabradorRetriever.openConnection
private URLConnection openConnection() throws IOException { final URLConnection connection = url.openConnection(); connection.setUseCaches(false); if (CONNECTION_TIMEOUT > 0) { connection.setConnectTimeout(CONNECTION_TIMEOUT); } if (READ_TIMEOUT > 0) { connection.setReadTimeout(READ_TIMEOUT); } // grâce à cette propriété, l'application retournera un flux compressé si la taille // dépasse x Ko connection.setRequestProperty("Accept-Encoding", "gzip"); if (headers != null) { for (final Map.Entry<String, String> entry : headers.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } if (url.getUserInfo() != null) { final String authorization = Base64Coder.encodeString(url.getUserInfo()); connection.setRequestProperty("Authorization", "Basic " + authorization); } return connection; }
java
private URLConnection openConnection() throws IOException { final URLConnection connection = url.openConnection(); connection.setUseCaches(false); if (CONNECTION_TIMEOUT > 0) { connection.setConnectTimeout(CONNECTION_TIMEOUT); } if (READ_TIMEOUT > 0) { connection.setReadTimeout(READ_TIMEOUT); } // grâce à cette propriété, l'application retournera un flux compressé si la taille // dépasse x Ko connection.setRequestProperty("Accept-Encoding", "gzip"); if (headers != null) { for (final Map.Entry<String, String> entry : headers.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } if (url.getUserInfo() != null) { final String authorization = Base64Coder.encodeString(url.getUserInfo()); connection.setRequestProperty("Authorization", "Basic " + authorization); } return connection; }
[ "private", "URLConnection", "openConnection", "(", ")", "throws", "IOException", "{", "final", "URLConnection", "connection", "=", "url", ".", "openConnection", "(", ")", ";", "connection", ".", "setUseCaches", "(", "false", ")", ";", "if", "(", "CONNECTION_TIMEOUT", ">", "0", ")", "{", "connection", ".", "setConnectTimeout", "(", "CONNECTION_TIMEOUT", ")", ";", "}", "if", "(", "READ_TIMEOUT", ">", "0", ")", "{", "connection", ".", "setReadTimeout", "(", "READ_TIMEOUT", ")", ";", "}", "// grâce à cette propriété, l'application retournera un flux compressé si la taille\r", "// dépasse x Ko\r", "connection", ".", "setRequestProperty", "(", "\"Accept-Encoding\"", ",", "\"gzip\"", ")", ";", "if", "(", "headers", "!=", "null", ")", "{", "for", "(", "final", "Map", ".", "Entry", "<", "String", ",", "String", ">", "entry", ":", "headers", ".", "entrySet", "(", ")", ")", "{", "connection", ".", "setRequestProperty", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "if", "(", "url", ".", "getUserInfo", "(", ")", "!=", "null", ")", "{", "final", "String", "authorization", "=", "Base64Coder", ".", "encodeString", "(", "url", ".", "getUserInfo", "(", ")", ")", ";", "connection", ".", "setRequestProperty", "(", "\"Authorization\"", ",", "\"Basic \"", "+", "authorization", ")", ";", "}", "return", "connection", ";", "}" ]
Ouvre la connection http. @return Object @throws IOException Exception de communication
[ "Ouvre", "la", "connection", "http", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/LabradorRetriever.java#L288-L310
19,341
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/LabradorRetriever.java
LabradorRetriever.createMockResultOfCall
@SuppressWarnings("unchecked") private <T> T createMockResultOfCall() throws IOException { final Object result; final String request = url.toString(); if (!request.contains(HttpParameter.PART.getName() + '=') && !request.contains(HttpParameter.JMX_VALUE.getName()) || request.contains(HttpPart.DEFAULT_WITH_CURRENT_REQUESTS.getName())) { final String message = request.contains("/test2") ? null : "ceci est message pour le rapport"; result = Arrays.asList(new Counter(Counter.HTTP_COUNTER_NAME, null), new Counter("services", null), new Counter(Counter.ERROR_COUNTER_NAME, null), new JavaInformations(null, true), message); } else { result = LabradorMock.createMockResultOfPartCall(request); } return (T) result; }
java
@SuppressWarnings("unchecked") private <T> T createMockResultOfCall() throws IOException { final Object result; final String request = url.toString(); if (!request.contains(HttpParameter.PART.getName() + '=') && !request.contains(HttpParameter.JMX_VALUE.getName()) || request.contains(HttpPart.DEFAULT_WITH_CURRENT_REQUESTS.getName())) { final String message = request.contains("/test2") ? null : "ceci est message pour le rapport"; result = Arrays.asList(new Counter(Counter.HTTP_COUNTER_NAME, null), new Counter("services", null), new Counter(Counter.ERROR_COUNTER_NAME, null), new JavaInformations(null, true), message); } else { result = LabradorMock.createMockResultOfPartCall(request); } return (T) result; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "<", "T", ">", "T", "createMockResultOfCall", "(", ")", "throws", "IOException", "{", "final", "Object", "result", ";", "final", "String", "request", "=", "url", ".", "toString", "(", ")", ";", "if", "(", "!", "request", ".", "contains", "(", "HttpParameter", ".", "PART", ".", "getName", "(", ")", "+", "'", "'", ")", "&&", "!", "request", ".", "contains", "(", "HttpParameter", ".", "JMX_VALUE", ".", "getName", "(", ")", ")", "||", "request", ".", "contains", "(", "HttpPart", ".", "DEFAULT_WITH_CURRENT_REQUESTS", ".", "getName", "(", ")", ")", ")", "{", "final", "String", "message", "=", "request", ".", "contains", "(", "\"/test2\"", ")", "?", "null", ":", "\"ceci est message pour le rapport\"", ";", "result", "=", "Arrays", ".", "asList", "(", "new", "Counter", "(", "Counter", ".", "HTTP_COUNTER_NAME", ",", "null", ")", ",", "new", "Counter", "(", "\"services\"", ",", "null", ")", ",", "new", "Counter", "(", "Counter", ".", "ERROR_COUNTER_NAME", ",", "null", ")", ",", "new", "JavaInformations", "(", "null", ",", "true", ")", ",", "message", ")", ";", "}", "else", "{", "result", "=", "LabradorMock", ".", "createMockResultOfPartCall", "(", "request", ")", ";", "}", "return", "(", "T", ")", "result", ";", "}" ]
bouchon pour tests unitaires
[ "bouchon", "pour", "tests", "unitaires" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/LabradorRetriever.java#L372-L388
19,342
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MExtensionFileFilter.java
MExtensionFileFilter.accept
@Override public boolean accept(final File file) { if (file != null) { if (file.isDirectory()) { return true; } final String extension = getExtension(file); if (extension != null && filters.containsKey(extension)) { return true; } } return false; }
java
@Override public boolean accept(final File file) { if (file != null) { if (file.isDirectory()) { return true; } final String extension = getExtension(file); if (extension != null && filters.containsKey(extension)) { return true; } } return false; }
[ "@", "Override", "public", "boolean", "accept", "(", "final", "File", "file", ")", "{", "if", "(", "file", "!=", "null", ")", "{", "if", "(", "file", ".", "isDirectory", "(", ")", ")", "{", "return", "true", ";", "}", "final", "String", "extension", "=", "getExtension", "(", "file", ")", ";", "if", "(", "extension", "!=", "null", "&&", "filters", ".", "containsKey", "(", "extension", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Return true if this file should be shown in the directory pane, false if it shouldn't. Files that begin with "." are ignored. @return boolean @param file File @see #getExtension @see javax.swing.filechooser.FileFilter#accept
[ "Return", "true", "if", "this", "file", "should", "be", "shown", "in", "the", "directory", "pane", "false", "if", "it", "shouldn", "t", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MExtensionFileFilter.java#L111-L124
19,343
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MExtensionFileFilter.java
MExtensionFileFilter.getExtension
public String getExtension(final File file) { if (file != null) { final String fileName = file.getName(); final int i = fileName.lastIndexOf('.'); if (i > 0 && i < fileName.length() - 1) { return fileName.substring(i + 1).toLowerCase(Locale.getDefault()); } } return null; }
java
public String getExtension(final File file) { if (file != null) { final String fileName = file.getName(); final int i = fileName.lastIndexOf('.'); if (i > 0 && i < fileName.length() - 1) { return fileName.substring(i + 1).toLowerCase(Locale.getDefault()); } } return null; }
[ "public", "String", "getExtension", "(", "final", "File", "file", ")", "{", "if", "(", "file", "!=", "null", ")", "{", "final", "String", "fileName", "=", "file", ".", "getName", "(", ")", ";", "final", "int", "i", "=", "fileName", ".", "lastIndexOf", "(", "'", "'", ")", ";", "if", "(", "i", ">", "0", "&&", "i", "<", "fileName", ".", "length", "(", ")", "-", "1", ")", "{", "return", "fileName", ".", "substring", "(", "i", "+", "1", ")", ".", "toLowerCase", "(", "Locale", ".", "getDefault", "(", ")", ")", ";", "}", "}", "return", "null", ";", "}" ]
Return the extension portion of the file's name. @return String @param file File
[ "Return", "the", "extension", "portion", "of", "the", "file", "s", "name", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MExtensionFileFilter.java#L193-L202
19,344
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/Main.java
Main.extractFromJar
private static File extractFromJar(String resource, String fileName, String suffix) throws IOException { final URL res = Main.class.getResource(resource); // put this jar in a file system so that we can load jars from there final File tmp; try { tmp = File.createTempFile(fileName, suffix); } catch (final IOException e) { final String tmpdir = System.getProperty("java.io.tmpdir"); throw new IllegalStateException( "JavaMelody has failed to create a temporary file in " + tmpdir, e); } final InputStream is = res.openStream(); try { final OutputStream os = new FileOutputStream(tmp); try { copyStream(is, os); } finally { os.close(); } } finally { is.close(); } tmp.deleteOnExit(); return tmp; }
java
private static File extractFromJar(String resource, String fileName, String suffix) throws IOException { final URL res = Main.class.getResource(resource); // put this jar in a file system so that we can load jars from there final File tmp; try { tmp = File.createTempFile(fileName, suffix); } catch (final IOException e) { final String tmpdir = System.getProperty("java.io.tmpdir"); throw new IllegalStateException( "JavaMelody has failed to create a temporary file in " + tmpdir, e); } final InputStream is = res.openStream(); try { final OutputStream os = new FileOutputStream(tmp); try { copyStream(is, os); } finally { os.close(); } } finally { is.close(); } tmp.deleteOnExit(); return tmp; }
[ "private", "static", "File", "extractFromJar", "(", "String", "resource", ",", "String", "fileName", ",", "String", "suffix", ")", "throws", "IOException", "{", "final", "URL", "res", "=", "Main", ".", "class", ".", "getResource", "(", "resource", ")", ";", "// put this jar in a file system so that we can load jars from there\r", "final", "File", "tmp", ";", "try", "{", "tmp", "=", "File", ".", "createTempFile", "(", "fileName", ",", "suffix", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "final", "String", "tmpdir", "=", "System", ".", "getProperty", "(", "\"java.io.tmpdir\"", ")", ";", "throw", "new", "IllegalStateException", "(", "\"JavaMelody has failed to create a temporary file in \"", "+", "tmpdir", ",", "e", ")", ";", "}", "final", "InputStream", "is", "=", "res", ".", "openStream", "(", ")", ";", "try", "{", "final", "OutputStream", "os", "=", "new", "FileOutputStream", "(", "tmp", ")", ";", "try", "{", "copyStream", "(", "is", ",", "os", ")", ";", "}", "finally", "{", "os", ".", "close", "(", ")", ";", "}", "}", "finally", "{", "is", ".", "close", "(", ")", ";", "}", "tmp", ".", "deleteOnExit", "(", ")", ";", "return", "tmp", ";", "}" ]
Extract a resource from jar, mark it for deletion upon exit, and return its location.
[ "Extract", "a", "resource", "from", "jar", "mark", "it", "for", "deletion", "upon", "exit", "and", "return", "its", "location", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/Main.java#L256-L282
19,345
javamelody/javamelody
javamelody-for-standalone/src/main/java/net/bull/javamelody/EmbeddedServer.java
EmbeddedServer.start
public static void start(int port, Map<Parameter, String> parameters) throws Exception { // Init jetty final Server server = new Server(port); final ContextHandlerCollection contexts = new ContextHandlerCollection(); final ServletContextHandler context = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS); final net.bull.javamelody.MonitoringFilter monitoringFilter = new net.bull.javamelody.MonitoringFilter(); monitoringFilter.setApplicationType("Standalone"); final FilterHolder filterHolder = new FilterHolder(monitoringFilter); if (parameters != null) { for (final Map.Entry<Parameter, String> entry : parameters.entrySet()) { final net.bull.javamelody.Parameter parameter = entry.getKey(); final String value = entry.getValue(); filterHolder.setInitParameter(parameter.getCode(), value); } } context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST)); final RequestLogHandler requestLogHandler = new RequestLogHandler(); contexts.addHandler(requestLogHandler); final HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] { contexts }); server.setHandler(handlers); server.start(); }
java
public static void start(int port, Map<Parameter, String> parameters) throws Exception { // Init jetty final Server server = new Server(port); final ContextHandlerCollection contexts = new ContextHandlerCollection(); final ServletContextHandler context = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS); final net.bull.javamelody.MonitoringFilter monitoringFilter = new net.bull.javamelody.MonitoringFilter(); monitoringFilter.setApplicationType("Standalone"); final FilterHolder filterHolder = new FilterHolder(monitoringFilter); if (parameters != null) { for (final Map.Entry<Parameter, String> entry : parameters.entrySet()) { final net.bull.javamelody.Parameter parameter = entry.getKey(); final String value = entry.getValue(); filterHolder.setInitParameter(parameter.getCode(), value); } } context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST)); final RequestLogHandler requestLogHandler = new RequestLogHandler(); contexts.addHandler(requestLogHandler); final HandlerCollection handlers = new HandlerCollection(); handlers.setHandlers(new Handler[] { contexts }); server.setHandler(handlers); server.start(); }
[ "public", "static", "void", "start", "(", "int", "port", ",", "Map", "<", "Parameter", ",", "String", ">", "parameters", ")", "throws", "Exception", "{", "// Init jetty\r", "final", "Server", "server", "=", "new", "Server", "(", "port", ")", ";", "final", "ContextHandlerCollection", "contexts", "=", "new", "ContextHandlerCollection", "(", ")", ";", "final", "ServletContextHandler", "context", "=", "new", "ServletContextHandler", "(", "contexts", ",", "\"/\"", ",", "ServletContextHandler", ".", "SESSIONS", ")", ";", "final", "net", ".", "bull", ".", "javamelody", ".", "MonitoringFilter", "monitoringFilter", "=", "new", "net", ".", "bull", ".", "javamelody", ".", "MonitoringFilter", "(", ")", ";", "monitoringFilter", ".", "setApplicationType", "(", "\"Standalone\"", ")", ";", "final", "FilterHolder", "filterHolder", "=", "new", "FilterHolder", "(", "monitoringFilter", ")", ";", "if", "(", "parameters", "!=", "null", ")", "{", "for", "(", "final", "Map", ".", "Entry", "<", "Parameter", ",", "String", ">", "entry", ":", "parameters", ".", "entrySet", "(", ")", ")", "{", "final", "net", ".", "bull", ".", "javamelody", ".", "Parameter", "parameter", "=", "entry", ".", "getKey", "(", ")", ";", "final", "String", "value", "=", "entry", ".", "getValue", "(", ")", ";", "filterHolder", ".", "setInitParameter", "(", "parameter", ".", "getCode", "(", ")", ",", "value", ")", ";", "}", "}", "context", ".", "addFilter", "(", "filterHolder", ",", "\"/*\"", ",", "EnumSet", ".", "of", "(", "DispatcherType", ".", "INCLUDE", ",", "DispatcherType", ".", "REQUEST", ")", ")", ";", "final", "RequestLogHandler", "requestLogHandler", "=", "new", "RequestLogHandler", "(", ")", ";", "contexts", ".", "addHandler", "(", "requestLogHandler", ")", ";", "final", "HandlerCollection", "handlers", "=", "new", "HandlerCollection", "(", ")", ";", "handlers", ".", "setHandlers", "(", "new", "Handler", "[", "]", "{", "contexts", "}", ")", ";", "server", ".", "setHandler", "(", "handlers", ")", ";", "server", ".", "start", "(", ")", ";", "}" ]
Start the server with a http port and optional javamelody parameters. @param port Http port @param parameters Optional javamelody parameters @throws Exception e
[ "Start", "the", "server", "with", "a", "http", "port", "and", "optional", "javamelody", "parameters", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-for-standalone/src/main/java/net/bull/javamelody/EmbeddedServer.java#L26-L54
19,346
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/HttpAuth.java
HttpAuth.isUserAuthorized
private boolean isUserAuthorized(HttpServletRequest httpRequest) { if (authorizedUsers == null) { return true; } // Get Authorization header final String auth = httpRequest.getHeader("Authorization"); if (auth == null) { return false; // no auth } if (!auth.toUpperCase(Locale.ENGLISH).startsWith("BASIC ")) { return false; // we only do BASIC } // Get encoded "user:password", comes after "BASIC " final String userpassEncoded = auth.substring("BASIC ".length()); // Decode it final String userpassDecoded = Base64Coder.decodeString(userpassEncoded); final boolean authOk = authorizedUsers.contains(userpassDecoded); return checkLockAgainstBruteForceAttack(authOk); }
java
private boolean isUserAuthorized(HttpServletRequest httpRequest) { if (authorizedUsers == null) { return true; } // Get Authorization header final String auth = httpRequest.getHeader("Authorization"); if (auth == null) { return false; // no auth } if (!auth.toUpperCase(Locale.ENGLISH).startsWith("BASIC ")) { return false; // we only do BASIC } // Get encoded "user:password", comes after "BASIC " final String userpassEncoded = auth.substring("BASIC ".length()); // Decode it final String userpassDecoded = Base64Coder.decodeString(userpassEncoded); final boolean authOk = authorizedUsers.contains(userpassDecoded); return checkLockAgainstBruteForceAttack(authOk); }
[ "private", "boolean", "isUserAuthorized", "(", "HttpServletRequest", "httpRequest", ")", "{", "if", "(", "authorizedUsers", "==", "null", ")", "{", "return", "true", ";", "}", "// Get Authorization header\r", "final", "String", "auth", "=", "httpRequest", ".", "getHeader", "(", "\"Authorization\"", ")", ";", "if", "(", "auth", "==", "null", ")", "{", "return", "false", ";", "// no auth\r", "}", "if", "(", "!", "auth", ".", "toUpperCase", "(", "Locale", ".", "ENGLISH", ")", ".", "startsWith", "(", "\"BASIC \"", ")", ")", "{", "return", "false", ";", "// we only do BASIC\r", "}", "// Get encoded \"user:password\", comes after \"BASIC \"\r", "final", "String", "userpassEncoded", "=", "auth", ".", "substring", "(", "\"BASIC \"", ".", "length", "(", ")", ")", ";", "// Decode it\r", "final", "String", "userpassDecoded", "=", "Base64Coder", ".", "decodeString", "(", "userpassEncoded", ")", ";", "final", "boolean", "authOk", "=", "authorizedUsers", ".", "contains", "(", "userpassDecoded", ")", ";", "return", "checkLockAgainstBruteForceAttack", "(", "authOk", ")", ";", "}" ]
Check if the user is authorized, when using the "authorized-users" parameter @param httpRequest HttpServletRequest @return true if the user is authorized
[ "Check", "if", "the", "user", "is", "authorized", "when", "using", "the", "authorized", "-", "users", "parameter" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/HttpAuth.java#L116-L135
19,347
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/SessionListener.java
SessionListener.invalidateAllSessionsExceptCurrentSession
public static void invalidateAllSessionsExceptCurrentSession(HttpSession currentSession) { for (final HttpSession session : SESSION_MAP_BY_ID.values()) { try { if (currentSession != null && currentSession.getId().equals(session.getId())) { // si l'utilisateur exécutant l'action a une session http, // on ne l'invalide pas continue; } session.invalidate(); } catch (final Exception e) { // Tomcat can throw "java.lang.IllegalStateException: getLastAccessedTime: Session already invalidated" continue; } } }
java
public static void invalidateAllSessionsExceptCurrentSession(HttpSession currentSession) { for (final HttpSession session : SESSION_MAP_BY_ID.values()) { try { if (currentSession != null && currentSession.getId().equals(session.getId())) { // si l'utilisateur exécutant l'action a une session http, // on ne l'invalide pas continue; } session.invalidate(); } catch (final Exception e) { // Tomcat can throw "java.lang.IllegalStateException: getLastAccessedTime: Session already invalidated" continue; } } }
[ "public", "static", "void", "invalidateAllSessionsExceptCurrentSession", "(", "HttpSession", "currentSession", ")", "{", "for", "(", "final", "HttpSession", "session", ":", "SESSION_MAP_BY_ID", ".", "values", "(", ")", ")", "{", "try", "{", "if", "(", "currentSession", "!=", "null", "&&", "currentSession", ".", "getId", "(", ")", ".", "equals", "(", "session", ".", "getId", "(", ")", ")", ")", "{", "// si l'utilisateur exécutant l'action a une session http,\r", "// on ne l'invalide pas\r", "continue", ";", "}", "session", ".", "invalidate", "(", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "// Tomcat can throw \"java.lang.IllegalStateException: getLastAccessedTime: Session already invalidated\"\r", "continue", ";", "}", "}", "}" ]
since 1.49
[ "since", "1", ".", "49" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/SessionListener.java#L160-L174
19,348
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/Base64Coder.java
Base64Coder.encodeLines
public static String encodeLines(byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) { final int blockLen = lineLen * 3 / 4; if (blockLen <= 0) { throw new IllegalArgumentException(); } final int lines = (iLen + blockLen - 1) / blockLen; final int bufLen = (iLen + 2) / 3 * 4 + lines * lineSeparator.length(); final StringBuilder buf = new StringBuilder(bufLen); int ip = 0; while (ip < iLen) { final int l = Math.min(iLen - ip, blockLen); buf.append(encode(in, iOff + ip, l)); buf.append(lineSeparator); ip += l; } return buf.toString(); }
java
public static String encodeLines(byte[] in, int iOff, int iLen, int lineLen, String lineSeparator) { final int blockLen = lineLen * 3 / 4; if (blockLen <= 0) { throw new IllegalArgumentException(); } final int lines = (iLen + blockLen - 1) / blockLen; final int bufLen = (iLen + 2) / 3 * 4 + lines * lineSeparator.length(); final StringBuilder buf = new StringBuilder(bufLen); int ip = 0; while (ip < iLen) { final int l = Math.min(iLen - ip, blockLen); buf.append(encode(in, iOff + ip, l)); buf.append(lineSeparator); ip += l; } return buf.toString(); }
[ "public", "static", "String", "encodeLines", "(", "byte", "[", "]", "in", ",", "int", "iOff", ",", "int", "iLen", ",", "int", "lineLen", ",", "String", "lineSeparator", ")", "{", "final", "int", "blockLen", "=", "lineLen", "*", "3", "/", "4", ";", "if", "(", "blockLen", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "final", "int", "lines", "=", "(", "iLen", "+", "blockLen", "-", "1", ")", "/", "blockLen", ";", "final", "int", "bufLen", "=", "(", "iLen", "+", "2", ")", "/", "3", "*", "4", "+", "lines", "*", "lineSeparator", ".", "length", "(", ")", ";", "final", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "bufLen", ")", ";", "int", "ip", "=", "0", ";", "while", "(", "ip", "<", "iLen", ")", "{", "final", "int", "l", "=", "Math", ".", "min", "(", "iLen", "-", "ip", ",", "blockLen", ")", ";", "buf", ".", "append", "(", "encode", "(", "in", ",", "iOff", "+", "ip", ",", "l", ")", ")", ";", "buf", ".", "append", "(", "lineSeparator", ")", ";", "ip", "+=", "l", ";", "}", "return", "buf", ".", "toString", "(", ")", ";", "}" ]
Encodes a byte array into Base 64 format and breaks the output into lines. @param in An array containing the data bytes to be encoded. @param iOff Offset of the first byte in <code>in</code> to be processed. @param iLen Number of bytes to be processed in <code>in</code>, starting at <code>iOff</code>. @param lineLen Line length for the output data. Should be a multiple of 4. @param lineSeparator The line separator to be used to separate the output lines. @return A String containing the Base64 encoded data, broken into lines.
[ "Encodes", "a", "byte", "array", "into", "Base", "64", "format", "and", "breaks", "the", "output", "into", "lines", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/Base64Coder.java#L99-L116
19,349
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/Base64Coder.java
Base64Coder.encode
public static char[] encode(byte[] in, int iOff, int iLen) { // NOPMD final int oDataLen = (iLen * 4 + 2) / 3; // output length without padding final int oLen = (iLen + 2) / 3 * 4; // output length including padding final char[] out = new char[oLen]; int ip = iOff; final int iEnd = iOff + iLen; int op = 0; while (ip < iEnd) { final int i0 = in[ip++] & 0xff; final int i1 = ip < iEnd ? in[ip++] & 0xff : 0; final int i2 = ip < iEnd ? in[ip++] & 0xff : 0; final int o0 = i0 >>> 2; final int o1 = (i0 & 3) << 4 | i1 >>> 4; final int o2 = (i1 & 0xf) << 2 | i2 >>> 6; final int o3 = i2 & 0x3F; out[op++] = MAP1[o0]; out[op++] = MAP1[o1]; out[op] = op < oDataLen ? MAP1[o2] : '='; op++; out[op] = op < oDataLen ? MAP1[o3] : '='; op++; } return out; }
java
public static char[] encode(byte[] in, int iOff, int iLen) { // NOPMD final int oDataLen = (iLen * 4 + 2) / 3; // output length without padding final int oLen = (iLen + 2) / 3 * 4; // output length including padding final char[] out = new char[oLen]; int ip = iOff; final int iEnd = iOff + iLen; int op = 0; while (ip < iEnd) { final int i0 = in[ip++] & 0xff; final int i1 = ip < iEnd ? in[ip++] & 0xff : 0; final int i2 = ip < iEnd ? in[ip++] & 0xff : 0; final int o0 = i0 >>> 2; final int o1 = (i0 & 3) << 4 | i1 >>> 4; final int o2 = (i1 & 0xf) << 2 | i2 >>> 6; final int o3 = i2 & 0x3F; out[op++] = MAP1[o0]; out[op++] = MAP1[o1]; out[op] = op < oDataLen ? MAP1[o2] : '='; op++; out[op] = op < oDataLen ? MAP1[o3] : '='; op++; } return out; }
[ "public", "static", "char", "[", "]", "encode", "(", "byte", "[", "]", "in", ",", "int", "iOff", ",", "int", "iLen", ")", "{", "// NOPMD\r", "final", "int", "oDataLen", "=", "(", "iLen", "*", "4", "+", "2", ")", "/", "3", ";", "// output length without padding\r", "final", "int", "oLen", "=", "(", "iLen", "+", "2", ")", "/", "3", "*", "4", ";", "// output length including padding\r", "final", "char", "[", "]", "out", "=", "new", "char", "[", "oLen", "]", ";", "int", "ip", "=", "iOff", ";", "final", "int", "iEnd", "=", "iOff", "+", "iLen", ";", "int", "op", "=", "0", ";", "while", "(", "ip", "<", "iEnd", ")", "{", "final", "int", "i0", "=", "in", "[", "ip", "++", "]", "&", "0xff", ";", "final", "int", "i1", "=", "ip", "<", "iEnd", "?", "in", "[", "ip", "++", "]", "&", "0xff", ":", "0", ";", "final", "int", "i2", "=", "ip", "<", "iEnd", "?", "in", "[", "ip", "++", "]", "&", "0xff", ":", "0", ";", "final", "int", "o0", "=", "i0", ">>>", "2", ";", "final", "int", "o1", "=", "(", "i0", "&", "3", ")", "<<", "4", "|", "i1", ">>>", "4", ";", "final", "int", "o2", "=", "(", "i1", "&", "0xf", ")", "<<", "2", "|", "i2", ">>>", "6", ";", "final", "int", "o3", "=", "i2", "&", "0x3F", ";", "out", "[", "op", "++", "]", "=", "MAP1", "[", "o0", "]", ";", "out", "[", "op", "++", "]", "=", "MAP1", "[", "o1", "]", ";", "out", "[", "op", "]", "=", "op", "<", "oDataLen", "?", "MAP1", "[", "o2", "]", ":", "'", "'", ";", "op", "++", ";", "out", "[", "op", "]", "=", "op", "<", "oDataLen", "?", "MAP1", "[", "o3", "]", ":", "'", "'", ";", "op", "++", ";", "}", "return", "out", ";", "}" ]
Encodes a byte array into Base64 format. No blanks or line breaks are inserted in the output. @param in An array containing the data bytes to be encoded. @param iOff Offset of the first byte in <code>in</code> to be processed. @param iLen Number of bytes to process in <code>in</code>, starting at <code>iOff</code>. @return A character array containing the Base64 encoded data.
[ "Encodes", "a", "byte", "array", "into", "Base64", "format", ".", "No", "blanks", "or", "line", "breaks", "are", "inserted", "in", "the", "output", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/Base64Coder.java#L147-L170
19,350
javamelody/javamelody
javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/JavaMelodyAutoConfiguration.java
JavaMelodyAutoConfiguration.defaultAdvisorAutoProxyCreator
@Bean @ConditionalOnMissingBean(DefaultAdvisorAutoProxyCreator.class) @ConditionalOnProperty(prefix = JavaMelodyConfigurationProperties.PREFIX, name = "advisor-auto-proxy-creator-enabled", matchIfMissing = false) public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { return new DefaultAdvisorAutoProxyCreator(); }
java
@Bean @ConditionalOnMissingBean(DefaultAdvisorAutoProxyCreator.class) @ConditionalOnProperty(prefix = JavaMelodyConfigurationProperties.PREFIX, name = "advisor-auto-proxy-creator-enabled", matchIfMissing = false) public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { return new DefaultAdvisorAutoProxyCreator(); }
[ "@", "Bean", "@", "ConditionalOnMissingBean", "(", "DefaultAdvisorAutoProxyCreator", ".", "class", ")", "@", "ConditionalOnProperty", "(", "prefix", "=", "JavaMelodyConfigurationProperties", ".", "PREFIX", ",", "name", "=", "\"advisor-auto-proxy-creator-enabled\"", ",", "matchIfMissing", "=", "false", ")", "public", "DefaultAdvisorAutoProxyCreator", "defaultAdvisorAutoProxyCreator", "(", ")", "{", "return", "new", "DefaultAdvisorAutoProxyCreator", "(", ")", ";", "}" ]
Now disabled by default, since dependency spring-boot-starter-aop was added in 1.76. @return DefaultAdvisorAutoProxyCreator
[ "Now", "disabled", "by", "default", "since", "dependency", "spring", "-", "boot", "-", "starter", "-", "aop", "was", "added", "in", "1", ".", "76", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/JavaMelodyAutoConfiguration.java#L181-L186
19,351
javamelody/javamelody
javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/JavaMelodyAutoConfiguration.java
JavaMelodyAutoConfiguration.monitoringFeignClientAdvisor
@SuppressWarnings("unchecked") @Bean @ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignClient") @ConditionalOnProperty(prefix = JavaMelodyConfigurationProperties.PREFIX, name = "spring-monitoring-enabled", matchIfMissing = true) // we check that the DefaultAdvisorAutoProxyCreator above is not enabled, because if it's enabled then feign calls are counted twice @ConditionalOnMissingBean(DefaultAdvisorAutoProxyCreator.class) public MonitoringSpringAdvisor monitoringFeignClientAdvisor() throws ClassNotFoundException { final Class<? extends Annotation> feignClientClass = (Class<? extends Annotation>) Class .forName("org.springframework.cloud.openfeign.FeignClient"); final MonitoringSpringAdvisor advisor = new MonitoringSpringAdvisor( new AnnotationMatchingPointcut(feignClientClass, true)); advisor.setAdvice(new MonitoringSpringInterceptor() { private static final long serialVersionUID = 1L; @Override protected String getRequestName(MethodInvocation invocation) { final StringBuilder sb = new StringBuilder(); final Method method = invocation.getMethod(); final RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); if (requestMapping != null) { String[] path = requestMapping.value(); if (path.length == 0) { path = requestMapping.path(); } if (path.length > 0) { sb.append(path[0]); sb.append(' '); if (requestMapping.method().length > 0) { sb.append(requestMapping.method()[0].name()); } else { sb.append("GET"); } sb.append('\n'); } } final Class<?> declaringClass = method.getDeclaringClass(); final String classPart = declaringClass.getSimpleName(); final String methodPart = method.getName(); sb.append(classPart).append('.').append(methodPart); return sb.toString(); } }); return advisor; }
java
@SuppressWarnings("unchecked") @Bean @ConditionalOnClass(name = "org.springframework.cloud.openfeign.FeignClient") @ConditionalOnProperty(prefix = JavaMelodyConfigurationProperties.PREFIX, name = "spring-monitoring-enabled", matchIfMissing = true) // we check that the DefaultAdvisorAutoProxyCreator above is not enabled, because if it's enabled then feign calls are counted twice @ConditionalOnMissingBean(DefaultAdvisorAutoProxyCreator.class) public MonitoringSpringAdvisor monitoringFeignClientAdvisor() throws ClassNotFoundException { final Class<? extends Annotation> feignClientClass = (Class<? extends Annotation>) Class .forName("org.springframework.cloud.openfeign.FeignClient"); final MonitoringSpringAdvisor advisor = new MonitoringSpringAdvisor( new AnnotationMatchingPointcut(feignClientClass, true)); advisor.setAdvice(new MonitoringSpringInterceptor() { private static final long serialVersionUID = 1L; @Override protected String getRequestName(MethodInvocation invocation) { final StringBuilder sb = new StringBuilder(); final Method method = invocation.getMethod(); final RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); if (requestMapping != null) { String[] path = requestMapping.value(); if (path.length == 0) { path = requestMapping.path(); } if (path.length > 0) { sb.append(path[0]); sb.append(' '); if (requestMapping.method().length > 0) { sb.append(requestMapping.method()[0].name()); } else { sb.append("GET"); } sb.append('\n'); } } final Class<?> declaringClass = method.getDeclaringClass(); final String classPart = declaringClass.getSimpleName(); final String methodPart = method.getName(); sb.append(classPart).append('.').append(methodPart); return sb.toString(); } }); return advisor; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "@", "Bean", "@", "ConditionalOnClass", "(", "name", "=", "\"org.springframework.cloud.openfeign.FeignClient\"", ")", "@", "ConditionalOnProperty", "(", "prefix", "=", "JavaMelodyConfigurationProperties", ".", "PREFIX", ",", "name", "=", "\"spring-monitoring-enabled\"", ",", "matchIfMissing", "=", "true", ")", "// we check that the DefaultAdvisorAutoProxyCreator above is not enabled, because if it's enabled then feign calls are counted twice", "@", "ConditionalOnMissingBean", "(", "DefaultAdvisorAutoProxyCreator", ".", "class", ")", "public", "MonitoringSpringAdvisor", "monitoringFeignClientAdvisor", "(", ")", "throws", "ClassNotFoundException", "{", "final", "Class", "<", "?", "extends", "Annotation", ">", "feignClientClass", "=", "(", "Class", "<", "?", "extends", "Annotation", ">", ")", "Class", ".", "forName", "(", "\"org.springframework.cloud.openfeign.FeignClient\"", ")", ";", "final", "MonitoringSpringAdvisor", "advisor", "=", "new", "MonitoringSpringAdvisor", "(", "new", "AnnotationMatchingPointcut", "(", "feignClientClass", ",", "true", ")", ")", ";", "advisor", ".", "setAdvice", "(", "new", "MonitoringSpringInterceptor", "(", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "@", "Override", "protected", "String", "getRequestName", "(", "MethodInvocation", "invocation", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "final", "Method", "method", "=", "invocation", ".", "getMethod", "(", ")", ";", "final", "RequestMapping", "requestMapping", "=", "method", ".", "getAnnotation", "(", "RequestMapping", ".", "class", ")", ";", "if", "(", "requestMapping", "!=", "null", ")", "{", "String", "[", "]", "path", "=", "requestMapping", ".", "value", "(", ")", ";", "if", "(", "path", ".", "length", "==", "0", ")", "{", "path", "=", "requestMapping", ".", "path", "(", ")", ";", "}", "if", "(", "path", ".", "length", ">", "0", ")", "{", "sb", ".", "append", "(", "path", "[", "0", "]", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "if", "(", "requestMapping", ".", "method", "(", ")", ".", "length", ">", "0", ")", "{", "sb", ".", "append", "(", "requestMapping", ".", "method", "(", ")", "[", "0", "]", ".", "name", "(", ")", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"GET\"", ")", ";", "}", "sb", ".", "append", "(", "'", "'", ")", ";", "}", "}", "final", "Class", "<", "?", ">", "declaringClass", "=", "method", ".", "getDeclaringClass", "(", ")", ";", "final", "String", "classPart", "=", "declaringClass", ".", "getSimpleName", "(", ")", ";", "final", "String", "methodPart", "=", "method", ".", "getName", "(", ")", ";", "sb", ".", "append", "(", "classPart", ")", ".", "append", "(", "'", "'", ")", ".", "append", "(", "methodPart", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "}", ")", ";", "return", "advisor", ";", "}" ]
Monitoring of Feign clients. @return MonitoringSpringAdvisor @throws ClassNotFoundException should not happen
[ "Monitoring", "of", "Feign", "clients", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-spring-boot-starter/src/main/java/net/bull/javamelody/JavaMelodyAutoConfiguration.java#L279-L322
19,352
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackendFactory.java
RrdNioBackendFactory.open
@Override protected RrdBackend open(String path, boolean readOnly) throws IOException { return new RrdNioBackend(path, readOnly, syncPeriod); }
java
@Override protected RrdBackend open(String path, boolean readOnly) throws IOException { return new RrdNioBackend(path, readOnly, syncPeriod); }
[ "@", "Override", "protected", "RrdBackend", "open", "(", "String", "path", ",", "boolean", "readOnly", ")", "throws", "IOException", "{", "return", "new", "RrdNioBackend", "(", "path", ",", "readOnly", ",", "syncPeriod", ")", ";", "}" ]
Creates RrdNioBackend object for the given file path. @param path File path @param readOnly True, if the file should be accessed in read/only mode. False otherwise. @return RrdNioBackend object which handles all I/O operations for the given file path @throws IOException Thrown in case of I/O error.
[ "Creates", "RrdNioBackend", "object", "for", "the", "given", "file", "path", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/RrdNioBackendFactory.java#L82-L85
19,353
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/MonitoringFilter.java
MonitoringFilter.registerApplicationNodeInCollectServer
public static void registerApplicationNodeInCollectServer(String applicationName, URL collectServerUrl, URL applicationNodeUrl) { if (collectServerUrl == null || applicationNodeUrl == null) { throw new IllegalArgumentException( "collectServerUrl and applicationNodeUrl must not be null"); } final String appName; if (applicationName == null) { appName = Parameters.getCurrentApplication(); } else { appName = applicationName; } final URL registerUrl; try { registerUrl = new URL(collectServerUrl.toExternalForm() + "?appName=" + URLEncoder.encode(appName, "UTF-8") + "&appUrls=" // "UTF-8" as said in javadoc + URLEncoder.encode(applicationNodeUrl.toExternalForm(), "UTF-8") + "&action=registerNode"); unregisterApplicationNodeInCollectServerUrl = new URL( registerUrl.toExternalForm().replace("registerNode", "unregisterNode")); } catch (final IOException e) { // can't happen if urls are ok throw new IllegalArgumentException(e); } // this is an asynchronous call because if this method is called when the webapp is starting, // the webapp can not respond to the collect server for the first collect of data final Thread thread = new Thread("javamelody registerApplicationNodeInCollectServer") { @Override public void run() { try { Thread.sleep(10000); } catch (final InterruptedException e) { throw new IllegalStateException(e); } try { new LabradorRetriever(registerUrl).post(null); LOG.info("application node added to the collect server"); } catch (final IOException e) { LOG.warn("Unable to register application's node in the collect server ( " + e + ')', e); } } }; thread.setDaemon(true); thread.start(); }
java
public static void registerApplicationNodeInCollectServer(String applicationName, URL collectServerUrl, URL applicationNodeUrl) { if (collectServerUrl == null || applicationNodeUrl == null) { throw new IllegalArgumentException( "collectServerUrl and applicationNodeUrl must not be null"); } final String appName; if (applicationName == null) { appName = Parameters.getCurrentApplication(); } else { appName = applicationName; } final URL registerUrl; try { registerUrl = new URL(collectServerUrl.toExternalForm() + "?appName=" + URLEncoder.encode(appName, "UTF-8") + "&appUrls=" // "UTF-8" as said in javadoc + URLEncoder.encode(applicationNodeUrl.toExternalForm(), "UTF-8") + "&action=registerNode"); unregisterApplicationNodeInCollectServerUrl = new URL( registerUrl.toExternalForm().replace("registerNode", "unregisterNode")); } catch (final IOException e) { // can't happen if urls are ok throw new IllegalArgumentException(e); } // this is an asynchronous call because if this method is called when the webapp is starting, // the webapp can not respond to the collect server for the first collect of data final Thread thread = new Thread("javamelody registerApplicationNodeInCollectServer") { @Override public void run() { try { Thread.sleep(10000); } catch (final InterruptedException e) { throw new IllegalStateException(e); } try { new LabradorRetriever(registerUrl).post(null); LOG.info("application node added to the collect server"); } catch (final IOException e) { LOG.warn("Unable to register application's node in the collect server ( " + e + ')', e); } } }; thread.setDaemon(true); thread.start(); }
[ "public", "static", "void", "registerApplicationNodeInCollectServer", "(", "String", "applicationName", ",", "URL", "collectServerUrl", ",", "URL", "applicationNodeUrl", ")", "{", "if", "(", "collectServerUrl", "==", "null", "||", "applicationNodeUrl", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"collectServerUrl and applicationNodeUrl must not be null\"", ")", ";", "}", "final", "String", "appName", ";", "if", "(", "applicationName", "==", "null", ")", "{", "appName", "=", "Parameters", ".", "getCurrentApplication", "(", ")", ";", "}", "else", "{", "appName", "=", "applicationName", ";", "}", "final", "URL", "registerUrl", ";", "try", "{", "registerUrl", "=", "new", "URL", "(", "collectServerUrl", ".", "toExternalForm", "(", ")", "+", "\"?appName=\"", "+", "URLEncoder", ".", "encode", "(", "appName", ",", "\"UTF-8\"", ")", "+", "\"&appUrls=\"", "// \"UTF-8\" as said in javadoc\r", "+", "URLEncoder", ".", "encode", "(", "applicationNodeUrl", ".", "toExternalForm", "(", ")", ",", "\"UTF-8\"", ")", "+", "\"&action=registerNode\"", ")", ";", "unregisterApplicationNodeInCollectServerUrl", "=", "new", "URL", "(", "registerUrl", ".", "toExternalForm", "(", ")", ".", "replace", "(", "\"registerNode\"", ",", "\"unregisterNode\"", ")", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "// can't happen if urls are ok\r", "throw", "new", "IllegalArgumentException", "(", "e", ")", ";", "}", "// this is an asynchronous call because if this method is called when the webapp is starting,\r", "// the webapp can not respond to the collect server for the first collect of data\r", "final", "Thread", "thread", "=", "new", "Thread", "(", "\"javamelody registerApplicationNodeInCollectServer\"", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "try", "{", "Thread", ".", "sleep", "(", "10000", ")", ";", "}", "catch", "(", "final", "InterruptedException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "e", ")", ";", "}", "try", "{", "new", "LabradorRetriever", "(", "registerUrl", ")", ".", "post", "(", "null", ")", ";", "LOG", ".", "info", "(", "\"application node added to the collect server\"", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "LOG", ".", "warn", "(", "\"Unable to register application's node in the collect server ( \"", "+", "e", "+", "'", "'", ",", "e", ")", ";", "}", "}", "}", ";", "thread", ".", "setDaemon", "(", "true", ")", ";", "thread", ".", "start", "(", ")", ";", "}" ]
Asynchronously calls the optional collect server to register this application's node to be monitored. @param applicationName Name of the application in the collect server:<br/> if it already exists the node will be added with the other nodes, if null name will be "contextPath_hostname". @param collectServerUrl Url of the collect server, for example http://11.22.33.44:8080 @param applicationNodeUrl Url of this application node to be called by the collect server, for example http://55.66.77.88:8080/mywebapp
[ "Asynchronously", "calls", "the", "optional", "collect", "server", "to", "register", "this", "application", "s", "node", "to", "be", "monitored", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/MonitoringFilter.java#L538-L585
19,354
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/MonitoringFilter.java
MonitoringFilter.unregisterApplicationNodeInCollectServer
public static void unregisterApplicationNodeInCollectServer() throws IOException { if (unregisterApplicationNodeInCollectServerUrl != null) { new LabradorRetriever(unregisterApplicationNodeInCollectServerUrl).post(null); LOG.info("application node removed from the collect server"); } }
java
public static void unregisterApplicationNodeInCollectServer() throws IOException { if (unregisterApplicationNodeInCollectServerUrl != null) { new LabradorRetriever(unregisterApplicationNodeInCollectServerUrl).post(null); LOG.info("application node removed from the collect server"); } }
[ "public", "static", "void", "unregisterApplicationNodeInCollectServer", "(", ")", "throws", "IOException", "{", "if", "(", "unregisterApplicationNodeInCollectServerUrl", "!=", "null", ")", "{", "new", "LabradorRetriever", "(", "unregisterApplicationNodeInCollectServerUrl", ")", ".", "post", "(", "null", ")", ";", "LOG", ".", "info", "(", "\"application node removed from the collect server\"", ")", ";", "}", "}" ]
Call the optional collect server to unregister this application's node. @throws IOException e
[ "Call", "the", "optional", "collect", "server", "to", "unregister", "this", "application", "s", "node", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/MonitoringFilter.java#L591-L596
19,355
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/common/Mailer.java
Mailer.send
public void send(String toAddress, String subject, String message, List<File> attachments, boolean highPriority) throws NamingException, MessagingException { assert toAddress != null; assert subject != null; assert message != null; final InternetAddress[] toAddresses = InternetAddress.parse(toAddress, false); final Message msg = new MimeMessage(getSession()); msg.setRecipients(Message.RecipientType.TO, toAddresses); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setFrom(fromAddress); if (highPriority) { msg.setHeader("X-Priority", "1"); msg.setHeader("x-msmail-priority", "high"); } // Content is stored in a MIME multi-part message with one body part final MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(message); final Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mbp); if (attachments != null && !attachments.isEmpty()) { for (final File attachment : attachments) { final DataSource source = new FileDataSource(attachment); final MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); } } msg.setContent(multipart); // protocol smtp, ou smpts si mail.transport.protocol=smtps est indiqué dans la configuration de la session mail String protocol = session.getProperty("mail.transport.protocol"); if (protocol == null) { protocol = "smtp"; } // authentification avec user et password si mail.smtp.auth=true (ou mail.smtps.auth=true) if (Boolean.parseBoolean(session.getProperty("mail." + protocol + ".auth"))) { final Transport tr = session.getTransport(protocol); try { tr.connect(session.getProperty("mail." + protocol + ".user"), session.getProperty("mail." + protocol + ".password")); msg.saveChanges(); // don't forget this tr.sendMessage(msg, msg.getAllRecipients()); } finally { tr.close(); } } else { Transport.send(msg); } }
java
public void send(String toAddress, String subject, String message, List<File> attachments, boolean highPriority) throws NamingException, MessagingException { assert toAddress != null; assert subject != null; assert message != null; final InternetAddress[] toAddresses = InternetAddress.parse(toAddress, false); final Message msg = new MimeMessage(getSession()); msg.setRecipients(Message.RecipientType.TO, toAddresses); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setFrom(fromAddress); if (highPriority) { msg.setHeader("X-Priority", "1"); msg.setHeader("x-msmail-priority", "high"); } // Content is stored in a MIME multi-part message with one body part final MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(message); final Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mbp); if (attachments != null && !attachments.isEmpty()) { for (final File attachment : attachments) { final DataSource source = new FileDataSource(attachment); final MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); } } msg.setContent(multipart); // protocol smtp, ou smpts si mail.transport.protocol=smtps est indiqué dans la configuration de la session mail String protocol = session.getProperty("mail.transport.protocol"); if (protocol == null) { protocol = "smtp"; } // authentification avec user et password si mail.smtp.auth=true (ou mail.smtps.auth=true) if (Boolean.parseBoolean(session.getProperty("mail." + protocol + ".auth"))) { final Transport tr = session.getTransport(protocol); try { tr.connect(session.getProperty("mail." + protocol + ".user"), session.getProperty("mail." + protocol + ".password")); msg.saveChanges(); // don't forget this tr.sendMessage(msg, msg.getAllRecipients()); } finally { tr.close(); } } else { Transport.send(msg); } }
[ "public", "void", "send", "(", "String", "toAddress", ",", "String", "subject", ",", "String", "message", ",", "List", "<", "File", ">", "attachments", ",", "boolean", "highPriority", ")", "throws", "NamingException", ",", "MessagingException", "{", "assert", "toAddress", "!=", "null", ";", "assert", "subject", "!=", "null", ";", "assert", "message", "!=", "null", ";", "final", "InternetAddress", "[", "]", "toAddresses", "=", "InternetAddress", ".", "parse", "(", "toAddress", ",", "false", ")", ";", "final", "Message", "msg", "=", "new", "MimeMessage", "(", "getSession", "(", ")", ")", ";", "msg", ".", "setRecipients", "(", "Message", ".", "RecipientType", ".", "TO", ",", "toAddresses", ")", ";", "msg", ".", "setSubject", "(", "subject", ")", ";", "msg", ".", "setSentDate", "(", "new", "Date", "(", ")", ")", ";", "msg", ".", "setFrom", "(", "fromAddress", ")", ";", "if", "(", "highPriority", ")", "{", "msg", ".", "setHeader", "(", "\"X-Priority\"", ",", "\"1\"", ")", ";", "msg", ".", "setHeader", "(", "\"x-msmail-priority\"", ",", "\"high\"", ")", ";", "}", "// Content is stored in a MIME multi-part message with one body part\r", "final", "MimeBodyPart", "mbp", "=", "new", "MimeBodyPart", "(", ")", ";", "mbp", ".", "setText", "(", "message", ")", ";", "final", "Multipart", "multipart", "=", "new", "MimeMultipart", "(", ")", ";", "multipart", ".", "addBodyPart", "(", "mbp", ")", ";", "if", "(", "attachments", "!=", "null", "&&", "!", "attachments", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "final", "File", "attachment", ":", "attachments", ")", "{", "final", "DataSource", "source", "=", "new", "FileDataSource", "(", "attachment", ")", ";", "final", "MimeBodyPart", "messageBodyPart", "=", "new", "MimeBodyPart", "(", ")", ";", "messageBodyPart", ".", "setDataHandler", "(", "new", "DataHandler", "(", "source", ")", ")", ";", "messageBodyPart", ".", "setFileName", "(", "attachment", ".", "getName", "(", ")", ")", ";", "multipart", ".", "addBodyPart", "(", "messageBodyPart", ")", ";", "}", "}", "msg", ".", "setContent", "(", "multipart", ")", ";", "// protocol smtp, ou smpts si mail.transport.protocol=smtps est indiqué dans la configuration de la session mail\r", "String", "protocol", "=", "session", ".", "getProperty", "(", "\"mail.transport.protocol\"", ")", ";", "if", "(", "protocol", "==", "null", ")", "{", "protocol", "=", "\"smtp\"", ";", "}", "// authentification avec user et password si mail.smtp.auth=true (ou mail.smtps.auth=true)\r", "if", "(", "Boolean", ".", "parseBoolean", "(", "session", ".", "getProperty", "(", "\"mail.\"", "+", "protocol", "+", "\".auth\"", ")", ")", ")", "{", "final", "Transport", "tr", "=", "session", ".", "getTransport", "(", "protocol", ")", ";", "try", "{", "tr", ".", "connect", "(", "session", ".", "getProperty", "(", "\"mail.\"", "+", "protocol", "+", "\".user\"", ")", ",", "session", ".", "getProperty", "(", "\"mail.\"", "+", "protocol", "+", "\".password\"", ")", ")", ";", "msg", ".", "saveChanges", "(", ")", ";", "// don't forget this\r", "tr", ".", "sendMessage", "(", "msg", ",", "msg", ".", "getAllRecipients", "(", ")", ")", ";", "}", "finally", "{", "tr", ".", "close", "(", ")", ";", "}", "}", "else", "{", "Transport", ".", "send", "(", "msg", ")", ";", "}", "}" ]
Envoie un mail. @param toAddress Adresses mails des destinataires séparées par des virgules. @param subject Titre du mail @param message Corps du mail @param attachments Liste de fichiers à attacher @param highPriority Priorité haute @throws NamingException e @throws MessagingException e
[ "Envoie", "un", "mail", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/common/Mailer.java#L136-L186
19,356
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MXmlWriter.java
MXmlWriter.writeXml
protected void writeXml(MListTable<?> table, OutputStream outputStream) throws IOException { final List<?> list = table.getList(); TransportFormatAdapter.writeXml((Serializable) list, outputStream); }
java
protected void writeXml(MListTable<?> table, OutputStream outputStream) throws IOException { final List<?> list = table.getList(); TransportFormatAdapter.writeXml((Serializable) list, outputStream); }
[ "protected", "void", "writeXml", "(", "MListTable", "<", "?", ">", "table", ",", "OutputStream", "outputStream", ")", "throws", "IOException", "{", "final", "List", "<", "?", ">", "list", "=", "table", ".", "getList", "(", ")", ";", "TransportFormatAdapter", ".", "writeXml", "(", "(", "Serializable", ")", "list", ",", "outputStream", ")", ";", "}" ]
Exporte une MListTable dans un fichier au format xml. @param table MListTable @param outputStream OutputStream @throws IOException Erreur disque
[ "Exporte", "une", "MListTable", "dans", "un", "fichier", "au", "format", "xml", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MXmlWriter.java#L73-L76
19,357
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/web/pdf/PdfDocumentFactory.java
PdfDocumentFactory.createWriter
private void createWriter(Document document, String title) throws DocumentException, IOException { final PdfWriter writer = PdfWriter.getInstance(document, output); //writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft); // title final HeaderFooter header = new HeaderFooter(new Phrase(title), false); header.setAlignment(Element.ALIGN_LEFT); header.setBorder(Rectangle.NO_BORDER); document.setHeader(header); // simple page numbers : x //HeaderFooter footer = new HeaderFooter(new Phrase(), true); //footer.setAlignment(Element.ALIGN_RIGHT); //footer.setBorder(Rectangle.TOP); //document.setFooter(footer); // add the event handler for advanced page numbers : x/y writer.setPageEvent(new PdfAdvancedPageNumberEvents()); }
java
private void createWriter(Document document, String title) throws DocumentException, IOException { final PdfWriter writer = PdfWriter.getInstance(document, output); //writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft); // title final HeaderFooter header = new HeaderFooter(new Phrase(title), false); header.setAlignment(Element.ALIGN_LEFT); header.setBorder(Rectangle.NO_BORDER); document.setHeader(header); // simple page numbers : x //HeaderFooter footer = new HeaderFooter(new Phrase(), true); //footer.setAlignment(Element.ALIGN_RIGHT); //footer.setBorder(Rectangle.TOP); //document.setFooter(footer); // add the event handler for advanced page numbers : x/y writer.setPageEvent(new PdfAdvancedPageNumberEvents()); }
[ "private", "void", "createWriter", "(", "Document", "document", ",", "String", "title", ")", "throws", "DocumentException", ",", "IOException", "{", "final", "PdfWriter", "writer", "=", "PdfWriter", ".", "getInstance", "(", "document", ",", "output", ")", ";", "//writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft);\r", "// title\r", "final", "HeaderFooter", "header", "=", "new", "HeaderFooter", "(", "new", "Phrase", "(", "title", ")", ",", "false", ")", ";", "header", ".", "setAlignment", "(", "Element", ".", "ALIGN_LEFT", ")", ";", "header", ".", "setBorder", "(", "Rectangle", ".", "NO_BORDER", ")", ";", "document", ".", "setHeader", "(", "header", ")", ";", "// simple page numbers : x\r", "//HeaderFooter footer = new HeaderFooter(new Phrase(), true);\r", "//footer.setAlignment(Element.ALIGN_RIGHT);\r", "//footer.setBorder(Rectangle.TOP);\r", "//document.setFooter(footer);\r", "// add the event handler for advanced page numbers : x/y\r", "writer", ".", "setPageEvent", "(", "new", "PdfAdvancedPageNumberEvents", "(", ")", ")", ";", "}" ]
We create a writer that listens to the document and directs a PDF-stream to output
[ "We", "create", "a", "writer", "that", "listens", "to", "the", "document", "and", "directs", "a", "PDF", "-", "stream", "to", "output" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/web/pdf/PdfDocumentFactory.java#L180-L199
19,358
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPdfWriter.java
MPdfWriter.writePdf
protected void writePdf(final MBasicTable table, final OutputStream out) throws IOException { try { // step 1: creation of a document-object final Rectangle pageSize = landscape ? PageSize.A4.rotate() : PageSize.A4; final Document document = new Document(pageSize, 50, 50, 50, 50); // step 2: we create a writer that listens to the document and directs a PDF-stream to out createWriter(table, document, out); // we add some meta information to the document, and we open it document.addAuthor(System.getProperty("user.name")); document.addCreator("JavaMelody"); final String title = buildTitle(table); if (title != null) { document.addTitle(title); } document.open(); // ouvre la boîte de dialogue Imprimer de Adobe Reader // if (writer instanceof PdfWriter) { // ((PdfWriter) writer).addJavaScript("this.print(true);", false); // } // table final Table datatable = new Table(table.getColumnCount()); datatable.setCellsFitPage(true); datatable.setPadding(4); datatable.setSpacing(0); // headers renderHeaders(table, datatable); // data rows renderList(table, datatable); document.add(datatable); // we close the document document.close(); } catch (final DocumentException e) { // on ne peut déclarer d'exception autre que IOException en throws throw new IOException(e); } }
java
protected void writePdf(final MBasicTable table, final OutputStream out) throws IOException { try { // step 1: creation of a document-object final Rectangle pageSize = landscape ? PageSize.A4.rotate() : PageSize.A4; final Document document = new Document(pageSize, 50, 50, 50, 50); // step 2: we create a writer that listens to the document and directs a PDF-stream to out createWriter(table, document, out); // we add some meta information to the document, and we open it document.addAuthor(System.getProperty("user.name")); document.addCreator("JavaMelody"); final String title = buildTitle(table); if (title != null) { document.addTitle(title); } document.open(); // ouvre la boîte de dialogue Imprimer de Adobe Reader // if (writer instanceof PdfWriter) { // ((PdfWriter) writer).addJavaScript("this.print(true);", false); // } // table final Table datatable = new Table(table.getColumnCount()); datatable.setCellsFitPage(true); datatable.setPadding(4); datatable.setSpacing(0); // headers renderHeaders(table, datatable); // data rows renderList(table, datatable); document.add(datatable); // we close the document document.close(); } catch (final DocumentException e) { // on ne peut déclarer d'exception autre que IOException en throws throw new IOException(e); } }
[ "protected", "void", "writePdf", "(", "final", "MBasicTable", "table", ",", "final", "OutputStream", "out", ")", "throws", "IOException", "{", "try", "{", "// step 1: creation of a document-object\r", "final", "Rectangle", "pageSize", "=", "landscape", "?", "PageSize", ".", "A4", ".", "rotate", "(", ")", ":", "PageSize", ".", "A4", ";", "final", "Document", "document", "=", "new", "Document", "(", "pageSize", ",", "50", ",", "50", ",", "50", ",", "50", ")", ";", "// step 2: we create a writer that listens to the document and directs a PDF-stream to out\r", "createWriter", "(", "table", ",", "document", ",", "out", ")", ";", "// we add some meta information to the document, and we open it\r", "document", ".", "addAuthor", "(", "System", ".", "getProperty", "(", "\"user.name\"", ")", ")", ";", "document", ".", "addCreator", "(", "\"JavaMelody\"", ")", ";", "final", "String", "title", "=", "buildTitle", "(", "table", ")", ";", "if", "(", "title", "!=", "null", ")", "{", "document", ".", "addTitle", "(", "title", ")", ";", "}", "document", ".", "open", "(", ")", ";", "// ouvre la boîte de dialogue Imprimer de Adobe Reader\r", "// if (writer instanceof PdfWriter) {\r", "// ((PdfWriter) writer).addJavaScript(\"this.print(true);\", false);\r", "// }\r", "// table\r", "final", "Table", "datatable", "=", "new", "Table", "(", "table", ".", "getColumnCount", "(", ")", ")", ";", "datatable", ".", "setCellsFitPage", "(", "true", ")", ";", "datatable", ".", "setPadding", "(", "4", ")", ";", "datatable", ".", "setSpacing", "(", "0", ")", ";", "// headers\r", "renderHeaders", "(", "table", ",", "datatable", ")", ";", "// data rows\r", "renderList", "(", "table", ",", "datatable", ")", ";", "document", ".", "add", "(", "datatable", ")", ";", "// we close the document\r", "document", ".", "close", "(", ")", ";", "}", "catch", "(", "final", "DocumentException", "e", ")", "{", "// on ne peut déclarer d'exception autre que IOException en throws\r", "throw", "new", "IOException", "(", "e", ")", ";", "}", "}" ]
Ecrit le pdf. @param table MBasicTable @param out OutputStream @throws IOException e
[ "Ecrit", "le", "pdf", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPdfWriter.java#L153-L195
19,359
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPdfWriter.java
MPdfWriter.createWriter
protected DocWriter createWriter(final MBasicTable table, final Document document, final OutputStream out) throws DocumentException { final PdfWriter writer = PdfWriter.getInstance(document, out); // writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft); // title if (table.getName() != null) { final HeaderFooter header = new HeaderFooter(new Phrase(table.getName()), false); header.setAlignment(Element.ALIGN_LEFT); header.setBorder(Rectangle.NO_BORDER); document.setHeader(header); document.addTitle(table.getName()); } // simple page numbers : x // HeaderFooter footer = new HeaderFooter(new Phrase(), true); // footer.setAlignment(Element.ALIGN_RIGHT); // footer.setBorder(Rectangle.TOP); // document.setFooter(footer); // add the event handler for advanced page numbers : x/y writer.setPageEvent(new AdvancedPageNumberEvents()); return writer; }
java
protected DocWriter createWriter(final MBasicTable table, final Document document, final OutputStream out) throws DocumentException { final PdfWriter writer = PdfWriter.getInstance(document, out); // writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft); // title if (table.getName() != null) { final HeaderFooter header = new HeaderFooter(new Phrase(table.getName()), false); header.setAlignment(Element.ALIGN_LEFT); header.setBorder(Rectangle.NO_BORDER); document.setHeader(header); document.addTitle(table.getName()); } // simple page numbers : x // HeaderFooter footer = new HeaderFooter(new Phrase(), true); // footer.setAlignment(Element.ALIGN_RIGHT); // footer.setBorder(Rectangle.TOP); // document.setFooter(footer); // add the event handler for advanced page numbers : x/y writer.setPageEvent(new AdvancedPageNumberEvents()); return writer; }
[ "protected", "DocWriter", "createWriter", "(", "final", "MBasicTable", "table", ",", "final", "Document", "document", ",", "final", "OutputStream", "out", ")", "throws", "DocumentException", "{", "final", "PdfWriter", "writer", "=", "PdfWriter", ".", "getInstance", "(", "document", ",", "out", ")", ";", "// writer.setViewerPreferences(PdfWriter.PageLayoutTwoColumnLeft);\r", "// title\r", "if", "(", "table", ".", "getName", "(", ")", "!=", "null", ")", "{", "final", "HeaderFooter", "header", "=", "new", "HeaderFooter", "(", "new", "Phrase", "(", "table", ".", "getName", "(", ")", ")", ",", "false", ")", ";", "header", ".", "setAlignment", "(", "Element", ".", "ALIGN_LEFT", ")", ";", "header", ".", "setBorder", "(", "Rectangle", ".", "NO_BORDER", ")", ";", "document", ".", "setHeader", "(", "header", ")", ";", "document", ".", "addTitle", "(", "table", ".", "getName", "(", ")", ")", ";", "}", "// simple page numbers : x\r", "// HeaderFooter footer = new HeaderFooter(new Phrase(), true);\r", "// footer.setAlignment(Element.ALIGN_RIGHT);\r", "// footer.setBorder(Rectangle.TOP);\r", "// document.setFooter(footer);\r", "// add the event handler for advanced page numbers : x/y\r", "writer", ".", "setPageEvent", "(", "new", "AdvancedPageNumberEvents", "(", ")", ")", ";", "return", "writer", ";", "}" ]
We create a writer that listens to the document and directs a PDF-stream to out @param table MBasicTable @param document Document @param out OutputStream @return DocWriter @throws DocumentException e
[ "We", "create", "a", "writer", "that", "listens", "to", "the", "document", "and", "directs", "a", "PDF", "-", "stream", "to", "out" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPdfWriter.java#L210-L234
19,360
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPdfWriter.java
MPdfWriter.renderHeaders
protected void renderHeaders(final MBasicTable table, final Table datatable) throws BadElementException { final int columnCount = table.getColumnCount(); final TableColumnModel columnModel = table.getColumnModel(); // size of columns float totalWidth = 0; for (int i = 0; i < columnCount; i++) { totalWidth += columnModel.getColumn(i).getWidth(); } final float[] headerwidths = new float[columnCount]; for (int i = 0; i < columnCount; i++) { headerwidths[i] = 100f * columnModel.getColumn(i).getWidth() / totalWidth; } datatable.setWidths(headerwidths); datatable.setWidth(100f); // table header final Font font = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD); datatable.getDefaultCell().setBorderWidth(2); datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // datatable.setDefaultCellGrayFill(0.75f); String text; Object value; for (int i = 0; i < columnCount; i++) { value = columnModel.getColumn(i).getHeaderValue(); text = value != null ? value.toString() : ""; datatable.addCell(new Phrase(text, font)); } // end of the table header datatable.endHeaders(); }
java
protected void renderHeaders(final MBasicTable table, final Table datatable) throws BadElementException { final int columnCount = table.getColumnCount(); final TableColumnModel columnModel = table.getColumnModel(); // size of columns float totalWidth = 0; for (int i = 0; i < columnCount; i++) { totalWidth += columnModel.getColumn(i).getWidth(); } final float[] headerwidths = new float[columnCount]; for (int i = 0; i < columnCount; i++) { headerwidths[i] = 100f * columnModel.getColumn(i).getWidth() / totalWidth; } datatable.setWidths(headerwidths); datatable.setWidth(100f); // table header final Font font = FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD); datatable.getDefaultCell().setBorderWidth(2); datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // datatable.setDefaultCellGrayFill(0.75f); String text; Object value; for (int i = 0; i < columnCount; i++) { value = columnModel.getColumn(i).getHeaderValue(); text = value != null ? value.toString() : ""; datatable.addCell(new Phrase(text, font)); } // end of the table header datatable.endHeaders(); }
[ "protected", "void", "renderHeaders", "(", "final", "MBasicTable", "table", ",", "final", "Table", "datatable", ")", "throws", "BadElementException", "{", "final", "int", "columnCount", "=", "table", ".", "getColumnCount", "(", ")", ";", "final", "TableColumnModel", "columnModel", "=", "table", ".", "getColumnModel", "(", ")", ";", "// size of columns\r", "float", "totalWidth", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "columnCount", ";", "i", "++", ")", "{", "totalWidth", "+=", "columnModel", ".", "getColumn", "(", "i", ")", ".", "getWidth", "(", ")", ";", "}", "final", "float", "[", "]", "headerwidths", "=", "new", "float", "[", "columnCount", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "columnCount", ";", "i", "++", ")", "{", "headerwidths", "[", "i", "]", "=", "100f", "*", "columnModel", ".", "getColumn", "(", "i", ")", ".", "getWidth", "(", ")", "/", "totalWidth", ";", "}", "datatable", ".", "setWidths", "(", "headerwidths", ")", ";", "datatable", ".", "setWidth", "(", "100f", ")", ";", "// table header\r", "final", "Font", "font", "=", "FontFactory", ".", "getFont", "(", "FontFactory", ".", "HELVETICA", ",", "12", ",", "Font", ".", "BOLD", ")", ";", "datatable", ".", "getDefaultCell", "(", ")", ".", "setBorderWidth", "(", "2", ")", ";", "datatable", ".", "getDefaultCell", "(", ")", ".", "setHorizontalAlignment", "(", "Element", ".", "ALIGN_CENTER", ")", ";", "// datatable.setDefaultCellGrayFill(0.75f);\r", "String", "text", ";", "Object", "value", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "columnCount", ";", "i", "++", ")", "{", "value", "=", "columnModel", ".", "getColumn", "(", "i", ")", ".", "getHeaderValue", "(", ")", ";", "text", "=", "value", "!=", "null", "?", "value", ".", "toString", "(", ")", ":", "\"\"", ";", "datatable", ".", "addCell", "(", "new", "Phrase", "(", "text", ",", "font", ")", ")", ";", "}", "// end of the table header\r", "datatable", ".", "endHeaders", "(", ")", ";", "}" ]
Effectue le rendu des headers. @param table MBasicTable @param datatable Table @throws BadElementException e
[ "Effectue", "le", "rendu", "des", "headers", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPdfWriter.java#L246-L277
19,361
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPdfWriter.java
MPdfWriter.renderList
protected void renderList(final MBasicTable table, final Table datatable) throws BadElementException { final int columnCount = table.getColumnCount(); final int rowCount = table.getRowCount(); // data rows final Font font = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL); datatable.getDefaultCell().setBorderWidth(1); datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); // datatable.setDefaultCellGrayFill(0); Object value; String text; int horizontalAlignment; for (int k = 0; k < rowCount; k++) { for (int i = 0; i < columnCount; i++) { value = getValueAt(table, k, i); if (value instanceof Number || value instanceof Date) { horizontalAlignment = Element.ALIGN_RIGHT; } else if (value instanceof Boolean) { horizontalAlignment = Element.ALIGN_CENTER; } else { horizontalAlignment = Element.ALIGN_LEFT; } datatable.getDefaultCell().setHorizontalAlignment(horizontalAlignment); text = getTextAt(table, k, i); datatable.addCell(new Phrase(8, text != null ? text : "", font)); } } }
java
protected void renderList(final MBasicTable table, final Table datatable) throws BadElementException { final int columnCount = table.getColumnCount(); final int rowCount = table.getRowCount(); // data rows final Font font = FontFactory.getFont(FontFactory.HELVETICA, 10, Font.NORMAL); datatable.getDefaultCell().setBorderWidth(1); datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); // datatable.setDefaultCellGrayFill(0); Object value; String text; int horizontalAlignment; for (int k = 0; k < rowCount; k++) { for (int i = 0; i < columnCount; i++) { value = getValueAt(table, k, i); if (value instanceof Number || value instanceof Date) { horizontalAlignment = Element.ALIGN_RIGHT; } else if (value instanceof Boolean) { horizontalAlignment = Element.ALIGN_CENTER; } else { horizontalAlignment = Element.ALIGN_LEFT; } datatable.getDefaultCell().setHorizontalAlignment(horizontalAlignment); text = getTextAt(table, k, i); datatable.addCell(new Phrase(8, text != null ? text : "", font)); } } }
[ "protected", "void", "renderList", "(", "final", "MBasicTable", "table", ",", "final", "Table", "datatable", ")", "throws", "BadElementException", "{", "final", "int", "columnCount", "=", "table", ".", "getColumnCount", "(", ")", ";", "final", "int", "rowCount", "=", "table", ".", "getRowCount", "(", ")", ";", "// data rows\r", "final", "Font", "font", "=", "FontFactory", ".", "getFont", "(", "FontFactory", ".", "HELVETICA", ",", "10", ",", "Font", ".", "NORMAL", ")", ";", "datatable", ".", "getDefaultCell", "(", ")", ".", "setBorderWidth", "(", "1", ")", ";", "datatable", ".", "getDefaultCell", "(", ")", ".", "setHorizontalAlignment", "(", "Element", ".", "ALIGN_LEFT", ")", ";", "// datatable.setDefaultCellGrayFill(0);\r", "Object", "value", ";", "String", "text", ";", "int", "horizontalAlignment", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "rowCount", ";", "k", "++", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "columnCount", ";", "i", "++", ")", "{", "value", "=", "getValueAt", "(", "table", ",", "k", ",", "i", ")", ";", "if", "(", "value", "instanceof", "Number", "||", "value", "instanceof", "Date", ")", "{", "horizontalAlignment", "=", "Element", ".", "ALIGN_RIGHT", ";", "}", "else", "if", "(", "value", "instanceof", "Boolean", ")", "{", "horizontalAlignment", "=", "Element", ".", "ALIGN_CENTER", ";", "}", "else", "{", "horizontalAlignment", "=", "Element", ".", "ALIGN_LEFT", ";", "}", "datatable", ".", "getDefaultCell", "(", ")", ".", "setHorizontalAlignment", "(", "horizontalAlignment", ")", ";", "text", "=", "getTextAt", "(", "table", ",", "k", ",", "i", ")", ";", "datatable", ".", "addCell", "(", "new", "Phrase", "(", "8", ",", "text", "!=", "null", "?", "text", ":", "\"\"", ",", "font", ")", ")", ";", "}", "}", "}" ]
Effectue le rendu de la liste. @param table MBasicTable @param datatable Table @throws BadElementException e
[ "Effectue", "le", "rendu", "de", "la", "liste", "." ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/print/MPdfWriter.java#L289-L316
19,362
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/PeriodCounterFactory.java
PeriodCounterFactory.getWeekCounter
Counter getWeekCounter() { final Counter weekCounter = createPeriodCounter("yyyyWW", currentDayCounter.getStartDate()); addRequestsAndErrorsForRange(weekCounter, Period.SEMAINE.getRange()); return weekCounter; }
java
Counter getWeekCounter() { final Counter weekCounter = createPeriodCounter("yyyyWW", currentDayCounter.getStartDate()); addRequestsAndErrorsForRange(weekCounter, Period.SEMAINE.getRange()); return weekCounter; }
[ "Counter", "getWeekCounter", "(", ")", "{", "final", "Counter", "weekCounter", "=", "createPeriodCounter", "(", "\"yyyyWW\"", ",", "currentDayCounter", ".", "getStartDate", "(", ")", ")", ";", "addRequestsAndErrorsForRange", "(", "weekCounter", ",", "Period", ".", "SEMAINE", ".", "getRange", "(", ")", ")", ";", "return", "weekCounter", ";", "}" ]
compteur des 7 derniers jours
[ "compteur", "des", "7", "derniers", "jours" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/PeriodCounterFactory.java#L84-L88
19,363
javamelody/javamelody
javamelody-core/src/main/java/net/bull/javamelody/internal/model/PeriodCounterFactory.java
PeriodCounterFactory.getYearCounter
Counter getYearCounter() throws IOException { final Counter yearCounter = createPeriodCounter("yyyy", currentDayCounter.getStartDate()); yearCounter.addRequestsAndErrors(currentDayCounter); final Calendar dayCalendar = Calendar.getInstance(); final int currentMonth = dayCalendar.get(Calendar.MONTH); dayCalendar.setTime(currentDayCounter.getStartDate()); dayCalendar.add(Calendar.DAY_OF_YEAR, -Period.ANNEE.getDurationDays() + 1); yearCounter.setStartDate(dayCalendar.getTime()); for (int i = 1; i < Period.ANNEE.getDurationDays(); i++) { if (dayCalendar.get(Calendar.DAY_OF_MONTH) == 1 && dayCalendar.get(Calendar.MONTH) != currentMonth) { // optimisation : on récupère les statistiques précédemment calculées pour ce mois entier // au lieu de parcourir à chaque fois les statistiques de chaque jour du mois yearCounter.addRequestsAndErrors(getMonthCounterAtDate(dayCalendar.getTime())); final int nbDaysInMonth = dayCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); // nbDaysInMonth - 1 puisque l'itération va ajouter 1 à i et à dayCalendar dayCalendar.add(Calendar.DAY_OF_YEAR, nbDaysInMonth - 1); i += nbDaysInMonth - 1; } else { yearCounter.addRequestsAndErrors(getDayCounterAtDate(dayCalendar.getTime())); } dayCalendar.add(Calendar.DAY_OF_YEAR, 1); } return yearCounter; }
java
Counter getYearCounter() throws IOException { final Counter yearCounter = createPeriodCounter("yyyy", currentDayCounter.getStartDate()); yearCounter.addRequestsAndErrors(currentDayCounter); final Calendar dayCalendar = Calendar.getInstance(); final int currentMonth = dayCalendar.get(Calendar.MONTH); dayCalendar.setTime(currentDayCounter.getStartDate()); dayCalendar.add(Calendar.DAY_OF_YEAR, -Period.ANNEE.getDurationDays() + 1); yearCounter.setStartDate(dayCalendar.getTime()); for (int i = 1; i < Period.ANNEE.getDurationDays(); i++) { if (dayCalendar.get(Calendar.DAY_OF_MONTH) == 1 && dayCalendar.get(Calendar.MONTH) != currentMonth) { // optimisation : on récupère les statistiques précédemment calculées pour ce mois entier // au lieu de parcourir à chaque fois les statistiques de chaque jour du mois yearCounter.addRequestsAndErrors(getMonthCounterAtDate(dayCalendar.getTime())); final int nbDaysInMonth = dayCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); // nbDaysInMonth - 1 puisque l'itération va ajouter 1 à i et à dayCalendar dayCalendar.add(Calendar.DAY_OF_YEAR, nbDaysInMonth - 1); i += nbDaysInMonth - 1; } else { yearCounter.addRequestsAndErrors(getDayCounterAtDate(dayCalendar.getTime())); } dayCalendar.add(Calendar.DAY_OF_YEAR, 1); } return yearCounter; }
[ "Counter", "getYearCounter", "(", ")", "throws", "IOException", "{", "final", "Counter", "yearCounter", "=", "createPeriodCounter", "(", "\"yyyy\"", ",", "currentDayCounter", ".", "getStartDate", "(", ")", ")", ";", "yearCounter", ".", "addRequestsAndErrors", "(", "currentDayCounter", ")", ";", "final", "Calendar", "dayCalendar", "=", "Calendar", ".", "getInstance", "(", ")", ";", "final", "int", "currentMonth", "=", "dayCalendar", ".", "get", "(", "Calendar", ".", "MONTH", ")", ";", "dayCalendar", ".", "setTime", "(", "currentDayCounter", ".", "getStartDate", "(", ")", ")", ";", "dayCalendar", ".", "add", "(", "Calendar", ".", "DAY_OF_YEAR", ",", "-", "Period", ".", "ANNEE", ".", "getDurationDays", "(", ")", "+", "1", ")", ";", "yearCounter", ".", "setStartDate", "(", "dayCalendar", ".", "getTime", "(", ")", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "Period", ".", "ANNEE", ".", "getDurationDays", "(", ")", ";", "i", "++", ")", "{", "if", "(", "dayCalendar", ".", "get", "(", "Calendar", ".", "DAY_OF_MONTH", ")", "==", "1", "&&", "dayCalendar", ".", "get", "(", "Calendar", ".", "MONTH", ")", "!=", "currentMonth", ")", "{", "// optimisation : on récupère les statistiques précédemment calculées pour ce mois entier\r", "// au lieu de parcourir à chaque fois les statistiques de chaque jour du mois\r", "yearCounter", ".", "addRequestsAndErrors", "(", "getMonthCounterAtDate", "(", "dayCalendar", ".", "getTime", "(", ")", ")", ")", ";", "final", "int", "nbDaysInMonth", "=", "dayCalendar", ".", "getActualMaximum", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ";", "// nbDaysInMonth - 1 puisque l'itération va ajouter 1 à i et à dayCalendar\r", "dayCalendar", ".", "add", "(", "Calendar", ".", "DAY_OF_YEAR", ",", "nbDaysInMonth", "-", "1", ")", ";", "i", "+=", "nbDaysInMonth", "-", "1", ";", "}", "else", "{", "yearCounter", ".", "addRequestsAndErrors", "(", "getDayCounterAtDate", "(", "dayCalendar", ".", "getTime", "(", ")", ")", ")", ";", "}", "dayCalendar", ".", "add", "(", "Calendar", ".", "DAY_OF_YEAR", ",", "1", ")", ";", "}", "return", "yearCounter", ";", "}" ]
compteur des 366 derniers jours
[ "compteur", "des", "366", "derniers", "jours" ]
18ad583ddeb5dcadd797dfda295409c6983ffd71
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-core/src/main/java/net/bull/javamelody/internal/model/PeriodCounterFactory.java#L121-L145
19,364
twitter/finagle
finagle-example/src/main/java/com/twitter/finagle/example/java/http/CatsDB.java
CatsDB.get
public Cat get(Integer id) { if (DB.isEmpty()) { addExampleCats(); } return DB.get(id); }
java
public Cat get(Integer id) { if (DB.isEmpty()) { addExampleCats(); } return DB.get(id); }
[ "public", "Cat", "get", "(", "Integer", "id", ")", "{", "if", "(", "DB", ".", "isEmpty", "(", ")", ")", "{", "addExampleCats", "(", ")", ";", "}", "return", "DB", ".", "get", "(", "id", ")", ";", "}" ]
Get the Cat for a given id.
[ "Get", "the", "Cat", "for", "a", "given", "id", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-example/src/main/java/com/twitter/finagle/example/java/http/CatsDB.java#L11-L17
19,365
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/ZooKeeperUtils.java
ZooKeeperUtils.isRetryable
public static boolean isRetryable(KeeperException e) { Objects.requireNonNull(e); switch (e.code()) { case CONNECTIONLOSS: case SESSIONEXPIRED: case SESSIONMOVED: case OPERATIONTIMEOUT: return true; case RUNTIMEINCONSISTENCY: case DATAINCONSISTENCY: case MARSHALLINGERROR: case BADARGUMENTS: case NONODE: case NOAUTH: case BADVERSION: case NOCHILDRENFOREPHEMERALS: case NODEEXISTS: case NOTEMPTY: case INVALIDCALLBACK: case INVALIDACL: case AUTHFAILED: case UNIMPLEMENTED: // These two should not be encountered - they are used internally by ZK to specify ranges case SYSTEMERROR: case APIERROR: case OK: // This is actually an invalid ZK exception code default: return false; } }
java
public static boolean isRetryable(KeeperException e) { Objects.requireNonNull(e); switch (e.code()) { case CONNECTIONLOSS: case SESSIONEXPIRED: case SESSIONMOVED: case OPERATIONTIMEOUT: return true; case RUNTIMEINCONSISTENCY: case DATAINCONSISTENCY: case MARSHALLINGERROR: case BADARGUMENTS: case NONODE: case NOAUTH: case BADVERSION: case NOCHILDRENFOREPHEMERALS: case NODEEXISTS: case NOTEMPTY: case INVALIDCALLBACK: case INVALIDACL: case AUTHFAILED: case UNIMPLEMENTED: // These two should not be encountered - they are used internally by ZK to specify ranges case SYSTEMERROR: case APIERROR: case OK: // This is actually an invalid ZK exception code default: return false; } }
[ "public", "static", "boolean", "isRetryable", "(", "KeeperException", "e", ")", "{", "Objects", ".", "requireNonNull", "(", "e", ")", ";", "switch", "(", "e", ".", "code", "(", ")", ")", "{", "case", "CONNECTIONLOSS", ":", "case", "SESSIONEXPIRED", ":", "case", "SESSIONMOVED", ":", "case", "OPERATIONTIMEOUT", ":", "return", "true", ";", "case", "RUNTIMEINCONSISTENCY", ":", "case", "DATAINCONSISTENCY", ":", "case", "MARSHALLINGERROR", ":", "case", "BADARGUMENTS", ":", "case", "NONODE", ":", "case", "NOAUTH", ":", "case", "BADVERSION", ":", "case", "NOCHILDRENFOREPHEMERALS", ":", "case", "NODEEXISTS", ":", "case", "NOTEMPTY", ":", "case", "INVALIDCALLBACK", ":", "case", "INVALIDACL", ":", "case", "AUTHFAILED", ":", "case", "UNIMPLEMENTED", ":", "// These two should not be encountered - they are used internally by ZK to specify ranges", "case", "SYSTEMERROR", ":", "case", "APIERROR", ":", "case", "OK", ":", "// This is actually an invalid ZK exception code", "default", ":", "return", "false", ";", "}", "}" ]
Returns true if the given exception indicates an error that can be resolved by retrying the operation without modification. @param e the exception to check @return true if the causing operation is strictly retryable
[ "Returns", "true", "if", "the", "given", "exception", "indicates", "an", "error", "that", "can", "be", "resolved", "by", "retrying", "the", "operation", "without", "modification", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/ZooKeeperUtils.java#L76-L110
19,366
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/base/MorePreconditions.java
MorePreconditions.checkNotBlank
public static String checkNotBlank(String argument) { Objects.requireNonNull(argument, ARG_NOT_BLANK_MSG); if (StringUtils.isBlank(argument)) { throw new IllegalArgumentException(ARG_NOT_BLANK_MSG); } return argument; }
java
public static String checkNotBlank(String argument) { Objects.requireNonNull(argument, ARG_NOT_BLANK_MSG); if (StringUtils.isBlank(argument)) { throw new IllegalArgumentException(ARG_NOT_BLANK_MSG); } return argument; }
[ "public", "static", "String", "checkNotBlank", "(", "String", "argument", ")", "{", "Objects", ".", "requireNonNull", "(", "argument", ",", "ARG_NOT_BLANK_MSG", ")", ";", "if", "(", "StringUtils", ".", "isBlank", "(", "argument", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "ARG_NOT_BLANK_MSG", ")", ";", "}", "return", "argument", ";", "}" ]
Checks that a string is both non-null and non-empty. @see #checkNotBlank(String, String, Object...)
[ "Checks", "that", "a", "string", "is", "both", "non", "-", "null", "and", "non", "-", "empty", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/base/MorePreconditions.java#L41-L47
19,367
twitter/finagle
finagle-example/src/main/java/com/twitter/finagle/example/java/http/JsonUtils.java
JsonUtils.toBytes
public static byte[] toBytes(Object value) { try { return mapper.writeValueAsBytes(value); } catch (Exception e) { System.out.println(e.getMessage()); throw new IllegalArgumentException( String.format("Could not transform to bytes: %s", e.getMessage())); } }
java
public static byte[] toBytes(Object value) { try { return mapper.writeValueAsBytes(value); } catch (Exception e) { System.out.println(e.getMessage()); throw new IllegalArgumentException( String.format("Could not transform to bytes: %s", e.getMessage())); } }
[ "public", "static", "byte", "[", "]", "toBytes", "(", "Object", "value", ")", "{", "try", "{", "return", "mapper", ".", "writeValueAsBytes", "(", "value", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "System", ".", "out", ".", "println", "(", "e", ".", "getMessage", "(", ")", ")", ";", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Could not transform to bytes: %s\"", ",", "e", ".", "getMessage", "(", ")", ")", ")", ";", "}", "}" ]
Convert an Object to an array of bytes.
[ "Convert", "an", "Object", "to", "an", "array", "of", "bytes", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-example/src/main/java/com/twitter/finagle/example/java/http/JsonUtils.java#L15-L23
19,368
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/ZooKeeperClient.java
ZooKeeperClient.digestCredentials
public static Credentials digestCredentials(String username, String password) { MorePreconditions.checkNotBlank(username); Objects.requireNonNull(password); // TODO(John Sirois): DigestAuthenticationProvider is broken - uses platform default charset // (on server) and so we just have to hope here that clients are deployed in compatible jvms. // Consider writing and installing a version of DigestAuthenticationProvider that controls its // Charset explicitly. return credentials("digest", (username + ":" + password).getBytes()); }
java
public static Credentials digestCredentials(String username, String password) { MorePreconditions.checkNotBlank(username); Objects.requireNonNull(password); // TODO(John Sirois): DigestAuthenticationProvider is broken - uses platform default charset // (on server) and so we just have to hope here that clients are deployed in compatible jvms. // Consider writing and installing a version of DigestAuthenticationProvider that controls its // Charset explicitly. return credentials("digest", (username + ":" + password).getBytes()); }
[ "public", "static", "Credentials", "digestCredentials", "(", "String", "username", ",", "String", "password", ")", "{", "MorePreconditions", ".", "checkNotBlank", "(", "username", ")", ";", "Objects", ".", "requireNonNull", "(", "password", ")", ";", "// TODO(John Sirois): DigestAuthenticationProvider is broken - uses platform default charset", "// (on server) and so we just have to hope here that clients are deployed in compatible jvms.", "// Consider writing and installing a version of DigestAuthenticationProvider that controls its", "// Charset explicitly.", "return", "credentials", "(", "\"digest\"", ",", "(", "username", "+", "\":\"", "+", "password", ")", ".", "getBytes", "(", ")", ")", ";", "}" ]
Creates a set of credentials for the zoo keeper digest authentication mechanism. @param username the username to authenticate with @param password the password to authenticate with @return a set of credentials that can be used to authenticate the zoo keeper client
[ "Creates", "a", "set", "of", "credentials", "for", "the", "zoo", "keeper", "digest", "authentication", "mechanism", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/ZooKeeperClient.java#L121-L130
19,369
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/ZooKeeperClient.java
ZooKeeperClient.get
public synchronized ZooKeeper get(Duration connectionTimeout) throws ZooKeeperConnectionException, InterruptedException, TimeoutException { if (zooKeeper == null) { final CountDownLatch connected = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { switch (event.getType()) { // Guard the None type since this watch may be used as the default watch on calls by // the client outside our control. case None: switch (event.getState()) { case Expired: LOG.info("Zookeeper session expired. Event: " + event); close(); break; case SyncConnected: connected.countDown(); break; default: break; // nop } break; default: break; // nop } eventQueue.offer(event); } }; try { zooKeeper = (sessionState != null) ? new ZooKeeper(connectString, sessionTimeoutMs, watcher, sessionState.sessionId, sessionState.sessionPasswd) : new ZooKeeper(connectString, sessionTimeoutMs, watcher); } catch (IOException e) { throw new ZooKeeperConnectionException( "Problem connecting to servers: " + zooKeeperServers, e); } if (connectionTimeout.inMillis() > 0) { if (!connected.await(connectionTimeout.inMillis(), TimeUnit.MILLISECONDS)) { close(); throw new TimeoutException("Timed out waiting for a ZK connection after " + connectionTimeout); } } else { try { connected.await(); } catch (InterruptedException ex) { LOG.info("Interrupted while waiting to connect to zooKeeper"); close(); throw ex; } } credentials.authenticate(zooKeeper); sessionState = new SessionState(zooKeeper.getSessionId(), zooKeeper.getSessionPasswd()); } return zooKeeper; }
java
public synchronized ZooKeeper get(Duration connectionTimeout) throws ZooKeeperConnectionException, InterruptedException, TimeoutException { if (zooKeeper == null) { final CountDownLatch connected = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { switch (event.getType()) { // Guard the None type since this watch may be used as the default watch on calls by // the client outside our control. case None: switch (event.getState()) { case Expired: LOG.info("Zookeeper session expired. Event: " + event); close(); break; case SyncConnected: connected.countDown(); break; default: break; // nop } break; default: break; // nop } eventQueue.offer(event); } }; try { zooKeeper = (sessionState != null) ? new ZooKeeper(connectString, sessionTimeoutMs, watcher, sessionState.sessionId, sessionState.sessionPasswd) : new ZooKeeper(connectString, sessionTimeoutMs, watcher); } catch (IOException e) { throw new ZooKeeperConnectionException( "Problem connecting to servers: " + zooKeeperServers, e); } if (connectionTimeout.inMillis() > 0) { if (!connected.await(connectionTimeout.inMillis(), TimeUnit.MILLISECONDS)) { close(); throw new TimeoutException("Timed out waiting for a ZK connection after " + connectionTimeout); } } else { try { connected.await(); } catch (InterruptedException ex) { LOG.info("Interrupted while waiting to connect to zooKeeper"); close(); throw ex; } } credentials.authenticate(zooKeeper); sessionState = new SessionState(zooKeeper.getSessionId(), zooKeeper.getSessionPasswd()); } return zooKeeper; }
[ "public", "synchronized", "ZooKeeper", "get", "(", "Duration", "connectionTimeout", ")", "throws", "ZooKeeperConnectionException", ",", "InterruptedException", ",", "TimeoutException", "{", "if", "(", "zooKeeper", "==", "null", ")", "{", "final", "CountDownLatch", "connected", "=", "new", "CountDownLatch", "(", "1", ")", ";", "Watcher", "watcher", "=", "new", "Watcher", "(", ")", "{", "@", "Override", "public", "void", "process", "(", "WatchedEvent", "event", ")", "{", "switch", "(", "event", ".", "getType", "(", ")", ")", "{", "// Guard the None type since this watch may be used as the default watch on calls by", "// the client outside our control.", "case", "None", ":", "switch", "(", "event", ".", "getState", "(", ")", ")", "{", "case", "Expired", ":", "LOG", ".", "info", "(", "\"Zookeeper session expired. Event: \"", "+", "event", ")", ";", "close", "(", ")", ";", "break", ";", "case", "SyncConnected", ":", "connected", ".", "countDown", "(", ")", ";", "break", ";", "default", ":", "break", ";", "// nop", "}", "break", ";", "default", ":", "break", ";", "// nop", "}", "eventQueue", ".", "offer", "(", "event", ")", ";", "}", "}", ";", "try", "{", "zooKeeper", "=", "(", "sessionState", "!=", "null", ")", "?", "new", "ZooKeeper", "(", "connectString", ",", "sessionTimeoutMs", ",", "watcher", ",", "sessionState", ".", "sessionId", ",", "sessionState", ".", "sessionPasswd", ")", ":", "new", "ZooKeeper", "(", "connectString", ",", "sessionTimeoutMs", ",", "watcher", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "ZooKeeperConnectionException", "(", "\"Problem connecting to servers: \"", "+", "zooKeeperServers", ",", "e", ")", ";", "}", "if", "(", "connectionTimeout", ".", "inMillis", "(", ")", ">", "0", ")", "{", "if", "(", "!", "connected", ".", "await", "(", "connectionTimeout", ".", "inMillis", "(", ")", ",", "TimeUnit", ".", "MILLISECONDS", ")", ")", "{", "close", "(", ")", ";", "throw", "new", "TimeoutException", "(", "\"Timed out waiting for a ZK connection after \"", "+", "connectionTimeout", ")", ";", "}", "}", "else", "{", "try", "{", "connected", ".", "await", "(", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "LOG", ".", "info", "(", "\"Interrupted while waiting to connect to zooKeeper\"", ")", ";", "close", "(", ")", ";", "throw", "ex", ";", "}", "}", "credentials", ".", "authenticate", "(", "zooKeeper", ")", ";", "sessionState", "=", "new", "SessionState", "(", "zooKeeper", ".", "getSessionId", "(", ")", ",", "zooKeeper", ".", "getSessionPasswd", "(", ")", ")", ";", "}", "return", "zooKeeper", ";", "}" ]
Returns the current active ZK connection or establishes a new one if none has yet been established or a previous connection was disconnected or had its session time out. This method will attempt to re-use sessions when possible. @param connectionTimeout the maximum amount of time to wait for the connection to the ZK cluster to be established; 0 to wait forever @return a connected ZooKeeper client @throws ZooKeeperConnectionException if there was a problem connecting to the ZK cluster @throws InterruptedException if interrupted while waiting for a connection to be established @throws TimeoutException if a connection could not be established within the configured session timeout
[ "Returns", "the", "current", "active", "ZK", "connection", "or", "establishes", "a", "new", "one", "if", "none", "has", "yet", "been", "established", "or", "a", "previous", "connection", "was", "disconnected", "or", "had", "its", "session", "time", "out", ".", "This", "method", "will", "attempt", "to", "re", "-", "use", "sessions", "when", "possible", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/ZooKeeperClient.java#L357-L418
19,370
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/Group.java
Group.getMemberId
public String getMemberId(String nodePath) { MorePreconditions.checkNotBlank(nodePath); if (!nodePath.startsWith(path + "/")) { throw new IllegalArgumentException( String.format("Not a member of this group[%s]: %s", path, nodePath)); } String memberId = StringUtils.substringAfterLast(nodePath, "/"); if (!nodeScheme.isMember(memberId)) { throw new IllegalArgumentException( String.format("Not a group member: %s", memberId)); } return memberId; }
java
public String getMemberId(String nodePath) { MorePreconditions.checkNotBlank(nodePath); if (!nodePath.startsWith(path + "/")) { throw new IllegalArgumentException( String.format("Not a member of this group[%s]: %s", path, nodePath)); } String memberId = StringUtils.substringAfterLast(nodePath, "/"); if (!nodeScheme.isMember(memberId)) { throw new IllegalArgumentException( String.format("Not a group member: %s", memberId)); } return memberId; }
[ "public", "String", "getMemberId", "(", "String", "nodePath", ")", "{", "MorePreconditions", ".", "checkNotBlank", "(", "nodePath", ")", ";", "if", "(", "!", "nodePath", ".", "startsWith", "(", "path", "+", "\"/\"", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Not a member of this group[%s]: %s\"", ",", "path", ",", "nodePath", ")", ")", ";", "}", "String", "memberId", "=", "StringUtils", ".", "substringAfterLast", "(", "nodePath", ",", "\"/\"", ")", ";", "if", "(", "!", "nodeScheme", ".", "isMember", "(", "memberId", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Not a group member: %s\"", ",", "memberId", ")", ")", ";", "}", "return", "memberId", ";", "}" ]
Returns the member id given a node path.
[ "Returns", "the", "member", "id", "given", "a", "node", "path", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/Group.java#L124-L138
19,371
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/Group.java
Group.getMemberIds
public Iterable<String> getMemberIds() throws ZooKeeperConnectionException, KeeperException, InterruptedException { return zkClient.get().getChildren(path, false) .stream() .filter(nodeNameFilter) .collect(Collectors.toList()); }
java
public Iterable<String> getMemberIds() throws ZooKeeperConnectionException, KeeperException, InterruptedException { return zkClient.get().getChildren(path, false) .stream() .filter(nodeNameFilter) .collect(Collectors.toList()); }
[ "public", "Iterable", "<", "String", ">", "getMemberIds", "(", ")", "throws", "ZooKeeperConnectionException", ",", "KeeperException", ",", "InterruptedException", "{", "return", "zkClient", ".", "get", "(", ")", ".", "getChildren", "(", "path", ",", "false", ")", ".", "stream", "(", ")", ".", "filter", "(", "nodeNameFilter", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}" ]
Returns the current list of group member ids by querying ZooKeeper synchronously. @return the ids of all the present members of this group @throws ZooKeeperConnectionException if there was a problem connecting to ZooKeeper @throws KeeperException if there was a problem reading this group's member ids @throws InterruptedException if this thread is interrupted listing the group members
[ "Returns", "the", "current", "list", "of", "group", "member", "ids", "by", "querying", "ZooKeeper", "synchronously", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/Group.java#L148-L154
19,372
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/Group.java
Group.getMemberData
public byte[] getMemberData(String memberId) throws ZooKeeperConnectionException, KeeperException, InterruptedException { return zkClient.get().getData(getMemberPath(memberId), false, null); }
java
public byte[] getMemberData(String memberId) throws ZooKeeperConnectionException, KeeperException, InterruptedException { return zkClient.get().getData(getMemberPath(memberId), false, null); }
[ "public", "byte", "[", "]", "getMemberData", "(", "String", "memberId", ")", "throws", "ZooKeeperConnectionException", ",", "KeeperException", ",", "InterruptedException", "{", "return", "zkClient", ".", "get", "(", ")", ".", "getData", "(", "getMemberPath", "(", "memberId", ")", ",", "false", ",", "null", ")", ";", "}" ]
Gets the data for one of this groups members by querying ZooKeeper synchronously. @param memberId the id of the member whose data to retrieve @return the data associated with the {@code memberId} @throws ZooKeeperConnectionException if there was a problem connecting to ZooKeeper @throws KeeperException if there was a problem reading this member's data @throws InterruptedException if this thread is interrupted retrieving the member data
[ "Gets", "the", "data", "for", "one", "of", "this", "groups", "members", "by", "querying", "ZooKeeper", "synchronously", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/Group.java#L165-L168
19,373
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/util/BackoffHelper.java
BackoffHelper.doUntilResult
public <T, E extends Exception> T doUntilResult(ExceptionalSupplier<T, E> task) throws InterruptedException, BackoffStoppedException, E { T result = task.get(); // give an immediate try return (result != null) ? result : retryWork(task); }
java
public <T, E extends Exception> T doUntilResult(ExceptionalSupplier<T, E> task) throws InterruptedException, BackoffStoppedException, E { T result = task.get(); // give an immediate try return (result != null) ? result : retryWork(task); }
[ "public", "<", "T", ",", "E", "extends", "Exception", ">", "T", "doUntilResult", "(", "ExceptionalSupplier", "<", "T", ",", "E", ">", "task", ")", "throws", "InterruptedException", ",", "BackoffStoppedException", ",", "E", "{", "T", "result", "=", "task", ".", "get", "(", ")", ";", "// give an immediate try", "return", "(", "result", "!=", "null", ")", "?", "result", ":", "retryWork", "(", "task", ")", ";", "}" ]
Executes the given task using the configured backoff strategy until the task succeeds as indicated by returning a non-null value. @param task the retryable task to execute until success @return the result of the successfully executed task @throws InterruptedException if interrupted while waiting for the task to execute successfully @throws BackoffStoppedException if the backoff stopped unsuccessfully @throws E if the task throws
[ "Executes", "the", "given", "task", "using", "the", "configured", "backoff", "strategy", "until", "the", "task", "succeeds", "as", "indicated", "by", "returning", "a", "non", "-", "null", "value", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/util/BackoffHelper.java#L118-L122
19,374
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/io/JsonCodec.java
JsonCodec.create
public static <T> JsonCodec<T> create(Class<T> clazz) { return new JsonCodec<T>(clazz, DefaultGsonHolder.INSTANCE); }
java
public static <T> JsonCodec<T> create(Class<T> clazz) { return new JsonCodec<T>(clazz, DefaultGsonHolder.INSTANCE); }
[ "public", "static", "<", "T", ">", "JsonCodec", "<", "T", ">", "create", "(", "Class", "<", "T", ">", "clazz", ")", "{", "return", "new", "JsonCodec", "<", "T", ">", "(", "clazz", ",", "DefaultGsonHolder", ".", "INSTANCE", ")", ";", "}" ]
Creates a new JSON codec instance for objects of the specified class. @param clazz the class of the objects the created codec is for. @return a newly constructed JSON codec instance for objects of the requested class.
[ "Creates", "a", "new", "JSON", "codec", "instance", "for", "objects", "of", "the", "specified", "class", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/io/JsonCodec.java#L53-L55
19,375
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/io/JsonCodec.java
JsonCodec.create
public static <T> JsonCodec<T> create(Class<T> clazz, Gson gson) { return new JsonCodec<T>(clazz, gson); }
java
public static <T> JsonCodec<T> create(Class<T> clazz, Gson gson) { return new JsonCodec<T>(clazz, gson); }
[ "public", "static", "<", "T", ">", "JsonCodec", "<", "T", ">", "create", "(", "Class", "<", "T", ">", "clazz", ",", "Gson", "gson", ")", "{", "return", "new", "JsonCodec", "<", "T", ">", "(", "clazz", ",", "gson", ")", ";", "}" ]
Creates a new JSON codec instance for objects of the specified class and the specified Gson instance. You can use this method if you need to customize the behavior of the Gson serializer. @param clazz the class of the objects the created codec is for. @param gson the Gson instance to use for serialization/deserialization. @return a newly constructed JSON codec instance for objects of the requested class.
[ "Creates", "a", "new", "JSON", "codec", "instance", "for", "objects", "of", "the", "specified", "class", "and", "the", "specified", "Gson", "instance", ".", "You", "can", "use", "this", "method", "if", "you", "need", "to", "customize", "the", "behavior", "of", "the", "Gson", "serializer", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/io/JsonCodec.java#L66-L68
19,376
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/ServerSets.java
ServerSets.serializeServiceInstance
public static byte[] serializeServiceInstance( ServiceInstance serviceInstance, Codec<ServiceInstance> codec) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); codec.serialize(serviceInstance, output); return output.toByteArray(); }
java
public static byte[] serializeServiceInstance( ServiceInstance serviceInstance, Codec<ServiceInstance> codec) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); codec.serialize(serviceInstance, output); return output.toByteArray(); }
[ "public", "static", "byte", "[", "]", "serializeServiceInstance", "(", "ServiceInstance", "serviceInstance", ",", "Codec", "<", "ServiceInstance", ">", "codec", ")", "throws", "IOException", "{", "ByteArrayOutputStream", "output", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "codec", ".", "serialize", "(", "serviceInstance", ",", "output", ")", ";", "return", "output", ".", "toByteArray", "(", ")", ";", "}" ]
Returns a serialized Thrift service instance object, with given endpoints and codec. @param serviceInstance the Thrift service instance object to be serialized @param codec the codec to use to serialize a Thrift service instance object @return byte array that contains a serialized Thrift service instance
[ "Returns", "a", "serialized", "Thrift", "service", "instance", "object", "with", "given", "endpoints", "and", "codec", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/ServerSets.java#L36-L42
19,377
twitter/finagle
finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/ServerSets.java
ServerSets.deserializeServiceInstance
public static ServiceInstance deserializeServiceInstance( byte[] data, Codec<ServiceInstance> codec) throws IOException { return codec.deserialize(new ByteArrayInputStream(data)); }
java
public static ServiceInstance deserializeServiceInstance( byte[] data, Codec<ServiceInstance> codec) throws IOException { return codec.deserialize(new ByteArrayInputStream(data)); }
[ "public", "static", "ServiceInstance", "deserializeServiceInstance", "(", "byte", "[", "]", "data", ",", "Codec", "<", "ServiceInstance", ">", "codec", ")", "throws", "IOException", "{", "return", "codec", ".", "deserialize", "(", "new", "ByteArrayInputStream", "(", "data", ")", ")", ";", "}" ]
Creates a service instance object deserialized from byte array. @param data the byte array contains a serialized Thrift service instance @param codec the codec to use to deserialize the byte array
[ "Creates", "a", "service", "instance", "object", "deserialized", "from", "byte", "array", "." ]
872be5f2b147fa50351bdbf08b003a26745e1df8
https://github.com/twitter/finagle/blob/872be5f2b147fa50351bdbf08b003a26745e1df8/finagle-serversets/src/main/java/com/twitter/finagle/common/zookeeper/ServerSets.java#L69-L73
19,378
JCTools/JCTools
jctools-channels/src/main/java/org/jctools/channels/proxy/ProxyChannelFactory.java
ProxyChannelFactory.createProxy
public static <E> ProxyChannel<E> createProxy(int capacity, Class<E> iFace, WaitStrategy waitStrategy, Class<? extends ProxyChannelRingBuffer> backendType) { if (!iFace.isInterface()) { throw new IllegalArgumentException("Not an interface: " + iFace); } String generatedName = Type.getInternalName(iFace) + "$JCTools$ProxyChannel$" + backendType.getSimpleName(); Class<?> preExisting = findExisting(generatedName, iFace); if (preExisting != null) { return instantiate(preExisting, capacity, waitStrategy); } List<Method> relevantMethods = findRelevantMethods(iFace); if (relevantMethods.isEmpty()) { throw new IllegalArgumentException("Does not declare any abstract methods: " + iFace); } // max number of reference arguments of any method int referenceMessageSize = 0; // max bytes required to store the primitive args of a call frame of any method int primitiveMessageSize = 0; for (Method method : relevantMethods) { int primitiveMethodSize = 0; int referenceCount = 0; for (Class<?> parameterType : method.getParameterTypes()) { if (parameterType.isPrimitive()) { primitiveMethodSize += primitiveMemorySize(parameterType); } else { referenceCount++; } } primitiveMessageSize = Math.max(primitiveMessageSize, primitiveMethodSize); referenceMessageSize = Math.max(referenceMessageSize, referenceCount); } // We need to add an int to this for the 'type' value on the message frame primitiveMessageSize += primitiveMemorySize(int.class); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); classWriter.visit(Opcodes.V1_4, Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, generatedName, null, Type.getInternalName(backendType), new String[]{Type.getInternalName(ProxyChannel.class), Type.getInternalName(iFace)}); implementInstanceFields(classWriter); implementConstructor(classWriter, backendType, generatedName, primitiveMessageSize, referenceMessageSize); implementProxyInstance(classWriter, iFace, generatedName); implementProxy(classWriter, iFace, generatedName); implementUserMethods(classWriter, relevantMethods, generatedName, backendType); implementProcess(classWriter, backendType, relevantMethods, iFace, generatedName); classWriter.visitEnd(); synchronized (ProxyChannelFactory.class) { preExisting = findExisting(generatedName, iFace); if (preExisting != null) { return instantiate(preExisting, capacity, waitStrategy); } byte[] byteCode = classWriter.toByteArray(); printClassBytes(byteCode); // Caveat: The interface and JCTools must be on the same class loader. Maybe class loader should be an argument? Overload? Class<?> definedClass = UnsafeAccess.UNSAFE.defineClass(generatedName, byteCode, 0, byteCode.length, iFace.getClassLoader(), null); return instantiate(definedClass, capacity, waitStrategy); } }
java
public static <E> ProxyChannel<E> createProxy(int capacity, Class<E> iFace, WaitStrategy waitStrategy, Class<? extends ProxyChannelRingBuffer> backendType) { if (!iFace.isInterface()) { throw new IllegalArgumentException("Not an interface: " + iFace); } String generatedName = Type.getInternalName(iFace) + "$JCTools$ProxyChannel$" + backendType.getSimpleName(); Class<?> preExisting = findExisting(generatedName, iFace); if (preExisting != null) { return instantiate(preExisting, capacity, waitStrategy); } List<Method> relevantMethods = findRelevantMethods(iFace); if (relevantMethods.isEmpty()) { throw new IllegalArgumentException("Does not declare any abstract methods: " + iFace); } // max number of reference arguments of any method int referenceMessageSize = 0; // max bytes required to store the primitive args of a call frame of any method int primitiveMessageSize = 0; for (Method method : relevantMethods) { int primitiveMethodSize = 0; int referenceCount = 0; for (Class<?> parameterType : method.getParameterTypes()) { if (parameterType.isPrimitive()) { primitiveMethodSize += primitiveMemorySize(parameterType); } else { referenceCount++; } } primitiveMessageSize = Math.max(primitiveMessageSize, primitiveMethodSize); referenceMessageSize = Math.max(referenceMessageSize, referenceCount); } // We need to add an int to this for the 'type' value on the message frame primitiveMessageSize += primitiveMemorySize(int.class); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); classWriter.visit(Opcodes.V1_4, Opcodes.ACC_SYNTHETIC | Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, generatedName, null, Type.getInternalName(backendType), new String[]{Type.getInternalName(ProxyChannel.class), Type.getInternalName(iFace)}); implementInstanceFields(classWriter); implementConstructor(classWriter, backendType, generatedName, primitiveMessageSize, referenceMessageSize); implementProxyInstance(classWriter, iFace, generatedName); implementProxy(classWriter, iFace, generatedName); implementUserMethods(classWriter, relevantMethods, generatedName, backendType); implementProcess(classWriter, backendType, relevantMethods, iFace, generatedName); classWriter.visitEnd(); synchronized (ProxyChannelFactory.class) { preExisting = findExisting(generatedName, iFace); if (preExisting != null) { return instantiate(preExisting, capacity, waitStrategy); } byte[] byteCode = classWriter.toByteArray(); printClassBytes(byteCode); // Caveat: The interface and JCTools must be on the same class loader. Maybe class loader should be an argument? Overload? Class<?> definedClass = UnsafeAccess.UNSAFE.defineClass(generatedName, byteCode, 0, byteCode.length, iFace.getClassLoader(), null); return instantiate(definedClass, capacity, waitStrategy); } }
[ "public", "static", "<", "E", ">", "ProxyChannel", "<", "E", ">", "createProxy", "(", "int", "capacity", ",", "Class", "<", "E", ">", "iFace", ",", "WaitStrategy", "waitStrategy", ",", "Class", "<", "?", "extends", "ProxyChannelRingBuffer", ">", "backendType", ")", "{", "if", "(", "!", "iFace", ".", "isInterface", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Not an interface: \"", "+", "iFace", ")", ";", "}", "String", "generatedName", "=", "Type", ".", "getInternalName", "(", "iFace", ")", "+", "\"$JCTools$ProxyChannel$\"", "+", "backendType", ".", "getSimpleName", "(", ")", ";", "Class", "<", "?", ">", "preExisting", "=", "findExisting", "(", "generatedName", ",", "iFace", ")", ";", "if", "(", "preExisting", "!=", "null", ")", "{", "return", "instantiate", "(", "preExisting", ",", "capacity", ",", "waitStrategy", ")", ";", "}", "List", "<", "Method", ">", "relevantMethods", "=", "findRelevantMethods", "(", "iFace", ")", ";", "if", "(", "relevantMethods", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Does not declare any abstract methods: \"", "+", "iFace", ")", ";", "}", "// max number of reference arguments of any method", "int", "referenceMessageSize", "=", "0", ";", "// max bytes required to store the primitive args of a call frame of any method", "int", "primitiveMessageSize", "=", "0", ";", "for", "(", "Method", "method", ":", "relevantMethods", ")", "{", "int", "primitiveMethodSize", "=", "0", ";", "int", "referenceCount", "=", "0", ";", "for", "(", "Class", "<", "?", ">", "parameterType", ":", "method", ".", "getParameterTypes", "(", ")", ")", "{", "if", "(", "parameterType", ".", "isPrimitive", "(", ")", ")", "{", "primitiveMethodSize", "+=", "primitiveMemorySize", "(", "parameterType", ")", ";", "}", "else", "{", "referenceCount", "++", ";", "}", "}", "primitiveMessageSize", "=", "Math", ".", "max", "(", "primitiveMessageSize", ",", "primitiveMethodSize", ")", ";", "referenceMessageSize", "=", "Math", ".", "max", "(", "referenceMessageSize", ",", "referenceCount", ")", ";", "}", "// We need to add an int to this for the 'type' value on the message frame", "primitiveMessageSize", "+=", "primitiveMemorySize", "(", "int", ".", "class", ")", ";", "ClassWriter", "classWriter", "=", "new", "ClassWriter", "(", "ClassWriter", ".", "COMPUTE_MAXS", ")", ";", "classWriter", ".", "visit", "(", "Opcodes", ".", "V1_4", ",", "Opcodes", ".", "ACC_SYNTHETIC", "|", "Opcodes", ".", "ACC_PUBLIC", "|", "Opcodes", ".", "ACC_FINAL", ",", "generatedName", ",", "null", ",", "Type", ".", "getInternalName", "(", "backendType", ")", ",", "new", "String", "[", "]", "{", "Type", ".", "getInternalName", "(", "ProxyChannel", ".", "class", ")", ",", "Type", ".", "getInternalName", "(", "iFace", ")", "}", ")", ";", "implementInstanceFields", "(", "classWriter", ")", ";", "implementConstructor", "(", "classWriter", ",", "backendType", ",", "generatedName", ",", "primitiveMessageSize", ",", "referenceMessageSize", ")", ";", "implementProxyInstance", "(", "classWriter", ",", "iFace", ",", "generatedName", ")", ";", "implementProxy", "(", "classWriter", ",", "iFace", ",", "generatedName", ")", ";", "implementUserMethods", "(", "classWriter", ",", "relevantMethods", ",", "generatedName", ",", "backendType", ")", ";", "implementProcess", "(", "classWriter", ",", "backendType", ",", "relevantMethods", ",", "iFace", ",", "generatedName", ")", ";", "classWriter", ".", "visitEnd", "(", ")", ";", "synchronized", "(", "ProxyChannelFactory", ".", "class", ")", "{", "preExisting", "=", "findExisting", "(", "generatedName", ",", "iFace", ")", ";", "if", "(", "preExisting", "!=", "null", ")", "{", "return", "instantiate", "(", "preExisting", ",", "capacity", ",", "waitStrategy", ")", ";", "}", "byte", "[", "]", "byteCode", "=", "classWriter", ".", "toByteArray", "(", ")", ";", "printClassBytes", "(", "byteCode", ")", ";", "// Caveat: The interface and JCTools must be on the same class loader. Maybe class loader should be an argument? Overload?", "Class", "<", "?", ">", "definedClass", "=", "UnsafeAccess", ".", "UNSAFE", ".", "defineClass", "(", "generatedName", ",", "byteCode", ",", "0", ",", "byteCode", ".", "length", ",", "iFace", ".", "getClassLoader", "(", ")", ",", "null", ")", ";", "return", "instantiate", "(", "definedClass", ",", "capacity", ",", "waitStrategy", ")", ";", "}", "}" ]
Create a proxy channel using a user supplied back end. @param capacity The minimum capacity for unprocessed invocations the channel should support @param iFace Interface the proxy must implement @param waitStrategy A wait strategy to be invoked when the backing data structure is full @param backendType The back end type, the proxy will inherit from this channel type. The back end type must define a constructor with signature: <code>(int capacity, int primitiveMessageSize, int referenceMessageSize)</code> @return A proxy channel instance
[ "Create", "a", "proxy", "channel", "using", "a", "user", "supplied", "back", "end", "." ]
9250fe316ec84209cbba0a41682f341256df781e
https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-channels/src/main/java/org/jctools/channels/proxy/ProxyChannelFactory.java#L111-L183
19,379
JCTools/JCTools
jctools-core/src/main/java/org/jctools/util/Pow2.java
Pow2.align
public static long align(final long value, final int alignment) { if (!isPowerOfTwo(alignment)) { throw new IllegalArgumentException("alignment must be a power of 2:" + alignment); } return (value + (alignment - 1)) & ~(alignment - 1); }
java
public static long align(final long value, final int alignment) { if (!isPowerOfTwo(alignment)) { throw new IllegalArgumentException("alignment must be a power of 2:" + alignment); } return (value + (alignment - 1)) & ~(alignment - 1); }
[ "public", "static", "long", "align", "(", "final", "long", "value", ",", "final", "int", "alignment", ")", "{", "if", "(", "!", "isPowerOfTwo", "(", "alignment", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"alignment must be a power of 2:\"", "+", "alignment", ")", ";", "}", "return", "(", "value", "+", "(", "alignment", "-", "1", ")", ")", "&", "~", "(", "alignment", "-", "1", ")", ";", "}" ]
Align a value to the next multiple up of alignment. If the value equals an alignment multiple then it is returned unchanged. @param value to be aligned up. @param alignment to be used, must be a power of 2. @return the value aligned to the next boundary.
[ "Align", "a", "value", "to", "the", "next", "multiple", "up", "of", "alignment", ".", "If", "the", "value", "equals", "an", "alignment", "multiple", "then", "it", "is", "returned", "unchanged", "." ]
9250fe316ec84209cbba0a41682f341256df781e
https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-core/src/main/java/org/jctools/util/Pow2.java#L55-L60
19,380
JCTools/JCTools
jctools-experimental/src/main/java/org/jctools/queues/MpscRelaxedArrayQueue.java
MpscRelaxedArrayQueue.isFull
private boolean isFull(final long producerPosition) { final long consumerPosition = lvConsumerPosition(); final long producerLimit = consumerPosition + this.cycleLength; if (producerPosition < producerLimit) { soProducerLimit(producerLimit); return false; } else { return true; } }
java
private boolean isFull(final long producerPosition) { final long consumerPosition = lvConsumerPosition(); final long producerLimit = consumerPosition + this.cycleLength; if (producerPosition < producerLimit) { soProducerLimit(producerLimit); return false; } else { return true; } }
[ "private", "boolean", "isFull", "(", "final", "long", "producerPosition", ")", "{", "final", "long", "consumerPosition", "=", "lvConsumerPosition", "(", ")", ";", "final", "long", "producerLimit", "=", "consumerPosition", "+", "this", ".", "cycleLength", ";", "if", "(", "producerPosition", "<", "producerLimit", ")", "{", "soProducerLimit", "(", "producerLimit", ")", ";", "return", "false", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Given the nature of getAndAdd progress on producerPosition and given the potential risk for over claiming it is quite possible for this method to report a queue which is not full as full.
[ "Given", "the", "nature", "of", "getAndAdd", "progress", "on", "producerPosition", "and", "given", "the", "potential", "risk", "for", "over", "claiming", "it", "is", "quite", "possible", "for", "this", "method", "to", "report", "a", "queue", "which", "is", "not", "full", "as", "full", "." ]
9250fe316ec84209cbba0a41682f341256df781e
https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-experimental/src/main/java/org/jctools/queues/MpscRelaxedArrayQueue.java#L321-L334
19,381
JCTools/JCTools
jctools-experimental/src/main/java/org/jctools/queues/MpscRelaxedArrayQueue.java
MpscRelaxedArrayQueue.fixProducerOverClaim
private boolean fixProducerOverClaim( final int activeCycleIndex, final long producerCycleClaim, final boolean slowProducer) { final long expectedProducerCycleClaim = producerCycleClaim + 1; //try to fix the overclaim bringing it back to a lower or a safe position if (!casProducerCycleClaim(activeCycleIndex, expectedProducerCycleClaim, producerCycleClaim)) { final long currentProducerCycleClaim = lvProducerCycleClaim(activeCycleIndex); //another producer has managed to fix the claim if (currentProducerCycleClaim <= producerCycleClaim) { return false; } if (slowProducer) { validateSlowProducerOverClaim(activeCycleIndex, producerCycleClaim); return true; } else { //the claim cannot be rolled back so It must be used as it is return true; } } return false; }
java
private boolean fixProducerOverClaim( final int activeCycleIndex, final long producerCycleClaim, final boolean slowProducer) { final long expectedProducerCycleClaim = producerCycleClaim + 1; //try to fix the overclaim bringing it back to a lower or a safe position if (!casProducerCycleClaim(activeCycleIndex, expectedProducerCycleClaim, producerCycleClaim)) { final long currentProducerCycleClaim = lvProducerCycleClaim(activeCycleIndex); //another producer has managed to fix the claim if (currentProducerCycleClaim <= producerCycleClaim) { return false; } if (slowProducer) { validateSlowProducerOverClaim(activeCycleIndex, producerCycleClaim); return true; } else { //the claim cannot be rolled back so It must be used as it is return true; } } return false; }
[ "private", "boolean", "fixProducerOverClaim", "(", "final", "int", "activeCycleIndex", ",", "final", "long", "producerCycleClaim", ",", "final", "boolean", "slowProducer", ")", "{", "final", "long", "expectedProducerCycleClaim", "=", "producerCycleClaim", "+", "1", ";", "//try to fix the overclaim bringing it back to a lower or a safe position", "if", "(", "!", "casProducerCycleClaim", "(", "activeCycleIndex", ",", "expectedProducerCycleClaim", ",", "producerCycleClaim", ")", ")", "{", "final", "long", "currentProducerCycleClaim", "=", "lvProducerCycleClaim", "(", "activeCycleIndex", ")", ";", "//another producer has managed to fix the claim", "if", "(", "currentProducerCycleClaim", "<=", "producerCycleClaim", ")", "{", "return", "false", ";", "}", "if", "(", "slowProducer", ")", "{", "validateSlowProducerOverClaim", "(", "activeCycleIndex", ",", "producerCycleClaim", ")", ";", "return", "true", ";", "}", "else", "{", "//the claim cannot be rolled back so It must be used as it is", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
It tries to fix a producer overclaim. @return {@code true} if the claim is now safe to be used,{@code false} otherwise and is needed to retry the claim.
[ "It", "tries", "to", "fix", "a", "producer", "overclaim", "." ]
9250fe316ec84209cbba0a41682f341256df781e
https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-experimental/src/main/java/org/jctools/queues/MpscRelaxedArrayQueue.java#L406-L433
19,382
JCTools/JCTools
jctools-channels/src/main/java/org/jctools/channels/OffHeapFixedMessageSizeRingBuffer.java
OffHeapFixedMessageSizeRingBuffer.writeReference
protected void writeReference(long offset, Object reference) { assert referenceMessageSize != 0 : "References are not in use"; // Is there a way to compute the element offset once and just // arithmetic? UnsafeRefArrayAccess.spElement(references, UnsafeRefArrayAccess.calcElementOffset(offset), reference); }
java
protected void writeReference(long offset, Object reference) { assert referenceMessageSize != 0 : "References are not in use"; // Is there a way to compute the element offset once and just // arithmetic? UnsafeRefArrayAccess.spElement(references, UnsafeRefArrayAccess.calcElementOffset(offset), reference); }
[ "protected", "void", "writeReference", "(", "long", "offset", ",", "Object", "reference", ")", "{", "assert", "referenceMessageSize", "!=", "0", ":", "\"References are not in use\"", ";", "// Is there a way to compute the element offset once and just", "// arithmetic?", "UnsafeRefArrayAccess", ".", "spElement", "(", "references", ",", "UnsafeRefArrayAccess", ".", "calcElementOffset", "(", "offset", ")", ",", "reference", ")", ";", "}" ]
Write a reference to the given position @param offset index into the reference array @param reference
[ "Write", "a", "reference", "to", "the", "given", "position" ]
9250fe316ec84209cbba0a41682f341256df781e
https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-channels/src/main/java/org/jctools/channels/OffHeapFixedMessageSizeRingBuffer.java#L248-L253
19,383
JCTools/JCTools
jctools-channels/src/main/java/org/jctools/channels/OffHeapFixedMessageSizeRingBuffer.java
OffHeapFixedMessageSizeRingBuffer.readReference
protected Object readReference(long offset) { assert referenceMessageSize != 0 : "References are not in use"; // Is there a way to compute the element offset once and just // arithmetic? return UnsafeRefArrayAccess.lpElement(references, UnsafeRefArrayAccess.calcElementOffset(offset)); }
java
protected Object readReference(long offset) { assert referenceMessageSize != 0 : "References are not in use"; // Is there a way to compute the element offset once and just // arithmetic? return UnsafeRefArrayAccess.lpElement(references, UnsafeRefArrayAccess.calcElementOffset(offset)); }
[ "protected", "Object", "readReference", "(", "long", "offset", ")", "{", "assert", "referenceMessageSize", "!=", "0", ":", "\"References are not in use\"", ";", "// Is there a way to compute the element offset once and just", "// arithmetic?", "return", "UnsafeRefArrayAccess", ".", "lpElement", "(", "references", ",", "UnsafeRefArrayAccess", ".", "calcElementOffset", "(", "offset", ")", ")", ";", "}" ]
Read a reference at the given position @param offset index into the reference array @return
[ "Read", "a", "reference", "at", "the", "given", "position" ]
9250fe316ec84209cbba0a41682f341256df781e
https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-channels/src/main/java/org/jctools/channels/OffHeapFixedMessageSizeRingBuffer.java#L260-L265
19,384
JCTools/JCTools
jctools-experimental/src/main/java/org/jctools/counters/FixedSizeStripedLongCounter.java
FixedSizeStripedLongCounter.probe
private int probe() { // Fast path for reliable well-distributed probe, available from JDK 7+. // As long as PROBE is final this branch will be inlined. if (PROBE != -1) { int probe; if ((probe = UNSAFE.getInt(Thread.currentThread(), PROBE)) == 0) { ThreadLocalRandom.current(); // force initialization probe = UNSAFE.getInt(Thread.currentThread(), PROBE); } return probe; } /* * Else use much worse (for values distribution) method: * Mix thread id with golden ratio and then xorshift it * to spread consecutive ids (see Knuth multiplicative method as reference). */ int probe = (int) ((Thread.currentThread().getId() * 0x9e3779b9) & Integer.MAX_VALUE); // xorshift probe ^= probe << 13; probe ^= probe >>> 17; probe ^= probe << 5; return probe; }
java
private int probe() { // Fast path for reliable well-distributed probe, available from JDK 7+. // As long as PROBE is final this branch will be inlined. if (PROBE != -1) { int probe; if ((probe = UNSAFE.getInt(Thread.currentThread(), PROBE)) == 0) { ThreadLocalRandom.current(); // force initialization probe = UNSAFE.getInt(Thread.currentThread(), PROBE); } return probe; } /* * Else use much worse (for values distribution) method: * Mix thread id with golden ratio and then xorshift it * to spread consecutive ids (see Knuth multiplicative method as reference). */ int probe = (int) ((Thread.currentThread().getId() * 0x9e3779b9) & Integer.MAX_VALUE); // xorshift probe ^= probe << 13; probe ^= probe >>> 17; probe ^= probe << 5; return probe; }
[ "private", "int", "probe", "(", ")", "{", "// Fast path for reliable well-distributed probe, available from JDK 7+.", "// As long as PROBE is final this branch will be inlined.", "if", "(", "PROBE", "!=", "-", "1", ")", "{", "int", "probe", ";", "if", "(", "(", "probe", "=", "UNSAFE", ".", "getInt", "(", "Thread", ".", "currentThread", "(", ")", ",", "PROBE", ")", ")", "==", "0", ")", "{", "ThreadLocalRandom", ".", "current", "(", ")", ";", "// force initialization", "probe", "=", "UNSAFE", ".", "getInt", "(", "Thread", ".", "currentThread", "(", ")", ",", "PROBE", ")", ";", "}", "return", "probe", ";", "}", "/*\n * Else use much worse (for values distribution) method:\n * Mix thread id with golden ratio and then xorshift it\n * to spread consecutive ids (see Knuth multiplicative method as reference).\n */", "int", "probe", "=", "(", "int", ")", "(", "(", "Thread", ".", "currentThread", "(", ")", ".", "getId", "(", ")", "*", "0x9e3779b9", ")", "&", "Integer", ".", "MAX_VALUE", ")", ";", "// xorshift", "probe", "^=", "probe", "<<", "13", ";", "probe", "^=", "probe", ">>>", "17", ";", "probe", "^=", "probe", "<<", "5", ";", "return", "probe", ";", "}" ]
Returns the probe value for the current thread. If target JDK version is 7 or higher, than ThreadLocalRandom-specific value will be used, xorshift with thread id otherwise.
[ "Returns", "the", "probe", "value", "for", "the", "current", "thread", ".", "If", "target", "JDK", "version", "is", "7", "or", "higher", "than", "ThreadLocalRandom", "-", "specific", "value", "will", "be", "used", "xorshift", "with", "thread", "id", "otherwise", "." ]
9250fe316ec84209cbba0a41682f341256df781e
https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-experimental/src/main/java/org/jctools/counters/FixedSizeStripedLongCounter.java#L109-L132
19,385
JCTools/JCTools
jctools-core/src/main/java/org/jctools/maps/ConcurrentAutoTable.java
ConcurrentAutoTable.set
public void set( long x ) { CAT newcat = new CAT(null,4,x); // Spin until CAS works while( !CAS_cat(_cat,newcat) ) {/*empty*/} }
java
public void set( long x ) { CAT newcat = new CAT(null,4,x); // Spin until CAS works while( !CAS_cat(_cat,newcat) ) {/*empty*/} }
[ "public", "void", "set", "(", "long", "x", ")", "{", "CAT", "newcat", "=", "new", "CAT", "(", "null", ",", "4", ",", "x", ")", ";", "// Spin until CAS works", "while", "(", "!", "CAS_cat", "(", "_cat", ",", "newcat", ")", ")", "{", "/*empty*/", "}", "}" ]
Atomically set the sum of the striped counters to specified value. Rather more expensive than a simple store, in order to remain atomic.
[ "Atomically", "set", "the", "sum", "of", "the", "striped", "counters", "to", "specified", "value", ".", "Rather", "more", "expensive", "than", "a", "simple", "store", "in", "order", "to", "remain", "atomic", "." ]
9250fe316ec84209cbba0a41682f341256df781e
https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-core/src/main/java/org/jctools/maps/ConcurrentAutoTable.java#L52-L56
19,386
JCTools/JCTools
jctools-build/src/main/java/org/jctools/queues/atomic/JavaParsingAtomicArrayQueueGenerator.java
JavaParsingAtomicArrayQueueGenerator.replaceParentClassesForAtomics
private void replaceParentClassesForAtomics(ClassOrInterfaceDeclaration n) { for (ClassOrInterfaceType parent : n.getExtendedTypes()) { if ("ConcurrentCircularArrayQueue".equals(parent.getNameAsString())) { parent.setName("AtomicReferenceArrayQueue"); } else if ("ConcurrentSequencedCircularArrayQueue".equals(parent.getNameAsString())) { parent.setName("SequencedAtomicReferenceArrayQueue"); } else { // Padded super classes are to be renamed and thus so does the // class we must extend. parent.setName(translateQueueName(parent.getNameAsString())); } } }
java
private void replaceParentClassesForAtomics(ClassOrInterfaceDeclaration n) { for (ClassOrInterfaceType parent : n.getExtendedTypes()) { if ("ConcurrentCircularArrayQueue".equals(parent.getNameAsString())) { parent.setName("AtomicReferenceArrayQueue"); } else if ("ConcurrentSequencedCircularArrayQueue".equals(parent.getNameAsString())) { parent.setName("SequencedAtomicReferenceArrayQueue"); } else { // Padded super classes are to be renamed and thus so does the // class we must extend. parent.setName(translateQueueName(parent.getNameAsString())); } } }
[ "private", "void", "replaceParentClassesForAtomics", "(", "ClassOrInterfaceDeclaration", "n", ")", "{", "for", "(", "ClassOrInterfaceType", "parent", ":", "n", ".", "getExtendedTypes", "(", ")", ")", "{", "if", "(", "\"ConcurrentCircularArrayQueue\"", ".", "equals", "(", "parent", ".", "getNameAsString", "(", ")", ")", ")", "{", "parent", ".", "setName", "(", "\"AtomicReferenceArrayQueue\"", ")", ";", "}", "else", "if", "(", "\"ConcurrentSequencedCircularArrayQueue\"", ".", "equals", "(", "parent", ".", "getNameAsString", "(", ")", ")", ")", "{", "parent", ".", "setName", "(", "\"SequencedAtomicReferenceArrayQueue\"", ")", ";", "}", "else", "{", "// Padded super classes are to be renamed and thus so does the", "// class we must extend.", "parent", ".", "setName", "(", "translateQueueName", "(", "parent", ".", "getNameAsString", "(", ")", ")", ")", ";", "}", "}", "}" ]
Searches all extended or implemented super classes or interfaces for special classes that differ with the atomics version and replaces them with the appropriate class. @param n
[ "Searches", "all", "extended", "or", "implemented", "super", "classes", "or", "interfaces", "for", "special", "classes", "that", "differ", "with", "the", "atomics", "version", "and", "replaces", "them", "with", "the", "appropriate", "class", "." ]
9250fe316ec84209cbba0a41682f341256df781e
https://github.com/JCTools/JCTools/blob/9250fe316ec84209cbba0a41682f341256df781e/jctools-build/src/main/java/org/jctools/queues/atomic/JavaParsingAtomicArrayQueueGenerator.java#L157-L169
19,387
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/ServiceInfo.java
ServiceInfo.of
public static ServiceInfo of(String serviceName, ServiceAcl... acls) { return new ServiceInfo(serviceName, TreePVector.from(Arrays.asList(acls))); }
java
public static ServiceInfo of(String serviceName, ServiceAcl... acls) { return new ServiceInfo(serviceName, TreePVector.from(Arrays.asList(acls))); }
[ "public", "static", "ServiceInfo", "of", "(", "String", "serviceName", ",", "ServiceAcl", "...", "acls", ")", "{", "return", "new", "ServiceInfo", "(", "serviceName", ",", "TreePVector", ".", "from", "(", "Arrays", ".", "asList", "(", "acls", ")", ")", ")", ";", "}" ]
Factory method to create ServiceInfo instances that contain a single locatable service. @param serviceName @param acls for the single locatableService of this Service. @return
[ "Factory", "method", "to", "create", "ServiceInfo", "instances", "that", "contain", "a", "single", "locatable", "service", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/ServiceInfo.java#L81-L83
19,388
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java
MessageProtocol.withContentType
public MessageProtocol withContentType(String contentType) { return new MessageProtocol(Optional.ofNullable(contentType), charset, version); }
java
public MessageProtocol withContentType(String contentType) { return new MessageProtocol(Optional.ofNullable(contentType), charset, version); }
[ "public", "MessageProtocol", "withContentType", "(", "String", "contentType", ")", "{", "return", "new", "MessageProtocol", "(", "Optional", ".", "ofNullable", "(", "contentType", ")", ",", "charset", ",", "version", ")", ";", "}" ]
Return a copy of this message protocol with the content type set to the given content type. @param contentType The content type to set. @return A copy of this message protocol.
[ "Return", "a", "copy", "of", "this", "message", "protocol", "with", "the", "content", "type", "set", "to", "the", "given", "content", "type", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java#L99-L101
19,389
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java
MessageProtocol.withCharset
public MessageProtocol withCharset(String charset) { return new MessageProtocol(contentType, Optional.ofNullable(charset), version); }
java
public MessageProtocol withCharset(String charset) { return new MessageProtocol(contentType, Optional.ofNullable(charset), version); }
[ "public", "MessageProtocol", "withCharset", "(", "String", "charset", ")", "{", "return", "new", "MessageProtocol", "(", "contentType", ",", "Optional", ".", "ofNullable", "(", "charset", ")", ",", "version", ")", ";", "}" ]
Return a copy of this message protocol with the charset set to the given charset. @param charset The charset to set. @return A copy of this message protocol.
[ "Return", "a", "copy", "of", "this", "message", "protocol", "with", "the", "charset", "set", "to", "the", "given", "charset", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java#L109-L111
19,390
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java
MessageProtocol.withVersion
public MessageProtocol withVersion(String version) { return new MessageProtocol(contentType, charset, Optional.ofNullable(version)); }
java
public MessageProtocol withVersion(String version) { return new MessageProtocol(contentType, charset, Optional.ofNullable(version)); }
[ "public", "MessageProtocol", "withVersion", "(", "String", "version", ")", "{", "return", "new", "MessageProtocol", "(", "contentType", ",", "charset", ",", "Optional", ".", "ofNullable", "(", "version", ")", ")", ";", "}" ]
Return a copy of this message protocol with the version set to the given version. @param version The version to set. @return A copy of this message protocol.
[ "Return", "a", "copy", "of", "this", "message", "protocol", "with", "the", "version", "set", "to", "the", "given", "version", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java#L119-L121
19,391
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java
MessageProtocol.isText
public boolean isText() { boolean isJson = contentType.map(contentType -> "application/json".equals(contentType)).orElse(false); boolean isPlainText = contentType.map(contentType -> "text/plain".equals(contentType)).orElse(false); return charset.isPresent() || isJson || isPlainText; }
java
public boolean isText() { boolean isJson = contentType.map(contentType -> "application/json".equals(contentType)).orElse(false); boolean isPlainText = contentType.map(contentType -> "text/plain".equals(contentType)).orElse(false); return charset.isPresent() || isJson || isPlainText; }
[ "public", "boolean", "isText", "(", ")", "{", "boolean", "isJson", "=", "contentType", ".", "map", "(", "contentType", "->", "\"application/json\"", ".", "equals", "(", "contentType", ")", ")", ".", "orElse", "(", "false", ")", ";", "boolean", "isPlainText", "=", "contentType", ".", "map", "(", "contentType", "->", "\"text/plain\"", ".", "equals", "(", "contentType", ")", ")", ".", "orElse", "(", "false", ")", ";", "return", "charset", ".", "isPresent", "(", ")", "||", "isJson", "||", "isPlainText", ";", "}" ]
Whether this message protocol is a text based protocol. This is determined by whether the charset is defined. @return true if this message protocol is text based.
[ "Whether", "this", "message", "protocol", "is", "a", "text", "based", "protocol", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java#L130-L135
19,392
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java
MessageProtocol.isUtf8
public boolean isUtf8() { if (charset.isPresent()) { return utf8Charset.equals(Charset.forName(charset.get())); } else { return false; } }
java
public boolean isUtf8() { if (charset.isPresent()) { return utf8Charset.equals(Charset.forName(charset.get())); } else { return false; } }
[ "public", "boolean", "isUtf8", "(", ")", "{", "if", "(", "charset", ".", "isPresent", "(", ")", ")", "{", "return", "utf8Charset", ".", "equals", "(", "Charset", ".", "forName", "(", "charset", ".", "get", "(", ")", ")", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Whether the protocol uses UTF-8. @return true if the charset used by this protocol is UTF-8, false if it's some other encoding or if no charset is defined.
[ "Whether", "the", "protocol", "uses", "UTF", "-", "8", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java#L145-L151
19,393
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java
MessageProtocol.toContentTypeHeader
public Optional<String> toContentTypeHeader() { return contentType.map(ct -> { if (charset.isPresent()) { return ct + "; charset=" + charset.get(); } else { return ct; } }); }
java
public Optional<String> toContentTypeHeader() { return contentType.map(ct -> { if (charset.isPresent()) { return ct + "; charset=" + charset.get(); } else { return ct; } }); }
[ "public", "Optional", "<", "String", ">", "toContentTypeHeader", "(", ")", "{", "return", "contentType", ".", "map", "(", "ct", "->", "{", "if", "(", "charset", ".", "isPresent", "(", ")", ")", "{", "return", "ct", "+", "\"; charset=\"", "+", "charset", ".", "get", "(", ")", ";", "}", "else", "{", "return", "ct", ";", "}", "}", ")", ";", "}" ]
Convert this message protocol to a content type header, if the content type is defined. @return The message protocol as a content type header.
[ "Convert", "this", "message", "protocol", "to", "a", "content", "type", "header", "if", "the", "content", "type", "is", "defined", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java#L158-L166
19,394
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java
MessageProtocol.fromContentTypeHeader
public static MessageProtocol fromContentTypeHeader(Optional<String> contentType) { return contentType.map(ct -> { String[] parts = ct.split(";"); String justContentType = parts[0]; Optional<String> charset = Optional.empty(); for (int i = 1; i < parts.length; i++) { String toTest = parts[i].trim(); if (toTest.startsWith("charset=")) { charset = Optional.of(toTest.split("=", 2)[1]); break; } } return new MessageProtocol(Optional.of(justContentType), charset, Optional.empty()); }).orElse(new MessageProtocol()); }
java
public static MessageProtocol fromContentTypeHeader(Optional<String> contentType) { return contentType.map(ct -> { String[] parts = ct.split(";"); String justContentType = parts[0]; Optional<String> charset = Optional.empty(); for (int i = 1; i < parts.length; i++) { String toTest = parts[i].trim(); if (toTest.startsWith("charset=")) { charset = Optional.of(toTest.split("=", 2)[1]); break; } } return new MessageProtocol(Optional.of(justContentType), charset, Optional.empty()); }).orElse(new MessageProtocol()); }
[ "public", "static", "MessageProtocol", "fromContentTypeHeader", "(", "Optional", "<", "String", ">", "contentType", ")", "{", "return", "contentType", ".", "map", "(", "ct", "->", "{", "String", "[", "]", "parts", "=", "ct", ".", "split", "(", "\";\"", ")", ";", "String", "justContentType", "=", "parts", "[", "0", "]", ";", "Optional", "<", "String", ">", "charset", "=", "Optional", ".", "empty", "(", ")", ";", "for", "(", "int", "i", "=", "1", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "String", "toTest", "=", "parts", "[", "i", "]", ".", "trim", "(", ")", ";", "if", "(", "toTest", ".", "startsWith", "(", "\"charset=\"", ")", ")", "{", "charset", "=", "Optional", ".", "of", "(", "toTest", ".", "split", "(", "\"=\"", ",", "2", ")", "[", "1", "]", ")", ";", "break", ";", "}", "}", "return", "new", "MessageProtocol", "(", "Optional", ".", "of", "(", "justContentType", ")", ",", "charset", ",", "Optional", ".", "empty", "(", ")", ")", ";", "}", ")", ".", "orElse", "(", "new", "MessageProtocol", "(", ")", ")", ";", "}" ]
Parse a message protocol from a content type header, if defined. @param contentType The content type header to parse. @return The parsed message protocol.
[ "Parse", "a", "message", "protocol", "from", "a", "content", "type", "header", "if", "defined", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/transport/MessageProtocol.java#L174-L188
19,395
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/deser/PathParamSerializers.java
PathParamSerializers.required
public static <Param> PathParamSerializer<Param> required(String name, Function<String, Param> deserialize, Function<Param, String> serialize) { return new NamedPathParamSerializer<Param>(name) { @Override public PSequence<String> serialize(Param parameter) { return TreePVector.singleton(serialize.apply(parameter)); } @Override public Param deserialize(PSequence<String> parameters) { if (parameters.isEmpty()) { throw new IllegalArgumentException(name + " parameter is required"); } else { return deserialize.apply(parameters.get(0)); } } }; }
java
public static <Param> PathParamSerializer<Param> required(String name, Function<String, Param> deserialize, Function<Param, String> serialize) { return new NamedPathParamSerializer<Param>(name) { @Override public PSequence<String> serialize(Param parameter) { return TreePVector.singleton(serialize.apply(parameter)); } @Override public Param deserialize(PSequence<String> parameters) { if (parameters.isEmpty()) { throw new IllegalArgumentException(name + " parameter is required"); } else { return deserialize.apply(parameters.get(0)); } } }; }
[ "public", "static", "<", "Param", ">", "PathParamSerializer", "<", "Param", ">", "required", "(", "String", "name", ",", "Function", "<", "String", ",", "Param", ">", "deserialize", ",", "Function", "<", "Param", ",", "String", ">", "serialize", ")", "{", "return", "new", "NamedPathParamSerializer", "<", "Param", ">", "(", "name", ")", "{", "@", "Override", "public", "PSequence", "<", "String", ">", "serialize", "(", "Param", "parameter", ")", "{", "return", "TreePVector", ".", "singleton", "(", "serialize", ".", "apply", "(", "parameter", ")", ")", ";", "}", "@", "Override", "public", "Param", "deserialize", "(", "PSequence", "<", "String", ">", "parameters", ")", "{", "if", "(", "parameters", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "name", "+", "\" parameter is required\"", ")", ";", "}", "else", "{", "return", "deserialize", ".", "apply", "(", "parameters", ".", "get", "(", "0", ")", ")", ";", "}", "}", "}", ";", "}" ]
Create a PathParamSerializer for required parameters.
[ "Create", "a", "PathParamSerializer", "for", "required", "parameters", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/deser/PathParamSerializers.java#L30-L47
19,396
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/deser/PathParamSerializers.java
PathParamSerializers.optional
public static <Param> PathParamSerializer<Optional<Param>> optional(String name, Function<String, Param> deserialize, Function<Param, String> serialize) { return new NamedPathParamSerializer<Optional<Param>>("Optional(" + name + ")") { @Override public PSequence<String> serialize(Optional<Param> parameter) { return parameter.map(p -> TreePVector.singleton(serialize.apply(p))).orElse(TreePVector.empty()); } @Override public Optional<Param> deserialize(PSequence<String> parameters) { if (parameters.isEmpty()) { return Optional.empty(); } else { return Optional.of(deserialize.apply(parameters.get(0))); } } }; }
java
public static <Param> PathParamSerializer<Optional<Param>> optional(String name, Function<String, Param> deserialize, Function<Param, String> serialize) { return new NamedPathParamSerializer<Optional<Param>>("Optional(" + name + ")") { @Override public PSequence<String> serialize(Optional<Param> parameter) { return parameter.map(p -> TreePVector.singleton(serialize.apply(p))).orElse(TreePVector.empty()); } @Override public Optional<Param> deserialize(PSequence<String> parameters) { if (parameters.isEmpty()) { return Optional.empty(); } else { return Optional.of(deserialize.apply(parameters.get(0))); } } }; }
[ "public", "static", "<", "Param", ">", "PathParamSerializer", "<", "Optional", "<", "Param", ">", ">", "optional", "(", "String", "name", ",", "Function", "<", "String", ",", "Param", ">", "deserialize", ",", "Function", "<", "Param", ",", "String", ">", "serialize", ")", "{", "return", "new", "NamedPathParamSerializer", "<", "Optional", "<", "Param", ">", ">", "(", "\"Optional(\"", "+", "name", "+", "\")\"", ")", "{", "@", "Override", "public", "PSequence", "<", "String", ">", "serialize", "(", "Optional", "<", "Param", ">", "parameter", ")", "{", "return", "parameter", ".", "map", "(", "p", "->", "TreePVector", ".", "singleton", "(", "serialize", ".", "apply", "(", "p", ")", ")", ")", ".", "orElse", "(", "TreePVector", ".", "empty", "(", ")", ")", ";", "}", "@", "Override", "public", "Optional", "<", "Param", ">", "deserialize", "(", "PSequence", "<", "String", ">", "parameters", ")", "{", "if", "(", "parameters", ".", "isEmpty", "(", ")", ")", "{", "return", "Optional", ".", "empty", "(", ")", ";", "}", "else", "{", "return", "Optional", ".", "of", "(", "deserialize", ".", "apply", "(", "parameters", ".", "get", "(", "0", ")", ")", ")", ";", "}", "}", "}", ";", "}" ]
Create a PathParamSerializer for optional parameters.
[ "Create", "a", "PathParamSerializer", "for", "optional", "parameters", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/deser/PathParamSerializers.java#L52-L71
19,397
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/deser/PathParamSerializers.java
PathParamSerializers.list
public static <Param> PathParamSerializer<List<Param>> list(String name, Function<PSequence<String>, Param> deserialize, Function<Param, PSequence<String>> serialize) { return new NamedPathParamSerializer<List<Param>>("List(" + name + ")") { @Override public PSequence<String> serialize(List<Param> parameter) { List<String> serializedParams = serializeCollection(parameter, serialize) .collect(Collectors.toList()); return TreePVector.from(serializedParams); } @Override public List<Param> deserialize(PSequence<String> parameters) { return deserializeCollection(parameters, deserialize).collect(Collectors.toList()); } }; }
java
public static <Param> PathParamSerializer<List<Param>> list(String name, Function<PSequence<String>, Param> deserialize, Function<Param, PSequence<String>> serialize) { return new NamedPathParamSerializer<List<Param>>("List(" + name + ")") { @Override public PSequence<String> serialize(List<Param> parameter) { List<String> serializedParams = serializeCollection(parameter, serialize) .collect(Collectors.toList()); return TreePVector.from(serializedParams); } @Override public List<Param> deserialize(PSequence<String> parameters) { return deserializeCollection(parameters, deserialize).collect(Collectors.toList()); } }; }
[ "public", "static", "<", "Param", ">", "PathParamSerializer", "<", "List", "<", "Param", ">", ">", "list", "(", "String", "name", ",", "Function", "<", "PSequence", "<", "String", ">", ",", "Param", ">", "deserialize", ",", "Function", "<", "Param", ",", "PSequence", "<", "String", ">", ">", "serialize", ")", "{", "return", "new", "NamedPathParamSerializer", "<", "List", "<", "Param", ">", ">", "(", "\"List(\"", "+", "name", "+", "\")\"", ")", "{", "@", "Override", "public", "PSequence", "<", "String", ">", "serialize", "(", "List", "<", "Param", ">", "parameter", ")", "{", "List", "<", "String", ">", "serializedParams", "=", "serializeCollection", "(", "parameter", ",", "serialize", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "return", "TreePVector", ".", "from", "(", "serializedParams", ")", ";", "}", "@", "Override", "public", "List", "<", "Param", ">", "deserialize", "(", "PSequence", "<", "String", ">", "parameters", ")", "{", "return", "deserializeCollection", "(", "parameters", ",", "deserialize", ")", ".", "collect", "(", "Collectors", ".", "toList", "(", ")", ")", ";", "}", "}", ";", "}" ]
Create a PathParamSerializer for List parameters.
[ "Create", "a", "PathParamSerializer", "for", "List", "parameters", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/deser/PathParamSerializers.java#L93-L111
19,398
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/deser/PathParamSerializers.java
PathParamSerializers.set
public static <Param> PathParamSerializer<Set<Param>> set(String name, Function<PSequence<String>, Param> deserialize, Function<Param, PSequence<String>> serialize) { return new NamedPathParamSerializer<Set<Param>>("Set(" + name + ")") { @Override public PSequence<String> serialize(Set<Param> parameter) { Set<String> serializedParams = serializeCollection(parameter, serialize) .collect(Collectors.toSet()); return TreePVector.from(serializedParams); } @Override public Set<Param> deserialize(PSequence<String> parameters) { return deserializeCollection(parameters, deserialize).collect(Collectors.toSet()); } }; }
java
public static <Param> PathParamSerializer<Set<Param>> set(String name, Function<PSequence<String>, Param> deserialize, Function<Param, PSequence<String>> serialize) { return new NamedPathParamSerializer<Set<Param>>("Set(" + name + ")") { @Override public PSequence<String> serialize(Set<Param> parameter) { Set<String> serializedParams = serializeCollection(parameter, serialize) .collect(Collectors.toSet()); return TreePVector.from(serializedParams); } @Override public Set<Param> deserialize(PSequence<String> parameters) { return deserializeCollection(parameters, deserialize).collect(Collectors.toSet()); } }; }
[ "public", "static", "<", "Param", ">", "PathParamSerializer", "<", "Set", "<", "Param", ">", ">", "set", "(", "String", "name", ",", "Function", "<", "PSequence", "<", "String", ">", ",", "Param", ">", "deserialize", ",", "Function", "<", "Param", ",", "PSequence", "<", "String", ">", ">", "serialize", ")", "{", "return", "new", "NamedPathParamSerializer", "<", "Set", "<", "Param", ">", ">", "(", "\"Set(\"", "+", "name", "+", "\")\"", ")", "{", "@", "Override", "public", "PSequence", "<", "String", ">", "serialize", "(", "Set", "<", "Param", ">", "parameter", ")", "{", "Set", "<", "String", ">", "serializedParams", "=", "serializeCollection", "(", "parameter", ",", "serialize", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "return", "TreePVector", ".", "from", "(", "serializedParams", ")", ";", "}", "@", "Override", "public", "Set", "<", "Param", ">", "deserialize", "(", "PSequence", "<", "String", ">", "parameters", ")", "{", "return", "deserializeCollection", "(", "parameters", ",", "deserialize", ")", ".", "collect", "(", "Collectors", ".", "toSet", "(", ")", ")", ";", "}", "}", ";", "}" ]
Create a PathParamSerializer for Set parameters.
[ "Create", "a", "PathParamSerializer", "for", "Set", "parameters", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/deser/PathParamSerializers.java#L117-L135
19,399
lagom/lagom
service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/deser/RawExceptionMessage.java
RawExceptionMessage.messageAsText
public String messageAsText() { if (protocol.charset().isPresent()) { return message.decodeString(protocol.charset().get()); } else { return Base64.getEncoder().encodeToString(message.toArray()); } }
java
public String messageAsText() { if (protocol.charset().isPresent()) { return message.decodeString(protocol.charset().get()); } else { return Base64.getEncoder().encodeToString(message.toArray()); } }
[ "public", "String", "messageAsText", "(", ")", "{", "if", "(", "protocol", ".", "charset", "(", ")", ".", "isPresent", "(", ")", ")", "{", "return", "message", ".", "decodeString", "(", "protocol", ".", "charset", "(", ")", ".", "get", "(", ")", ")", ";", "}", "else", "{", "return", "Base64", ".", "getEncoder", "(", ")", ".", "encodeToString", "(", "message", ".", "toArray", "(", ")", ")", ";", "}", "}" ]
Get the message as text. If this is a binary message (that is, the message protocol does not define a charset), encodes it using Base64. @return The message as text.
[ "Get", "the", "message", "as", "text", "." ]
3763055a9d1aace793a5d970f4e688aea61b1a5a
https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/deser/RawExceptionMessage.java#L73-L79