file_id
int64 1
46.7k
| content
stringlengths 14
344k
| repo
stringlengths 7
109
| path
stringlengths 8
171
|
---|---|---|---|
45,335 | package com.mxgraph.online;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.nio.file.Path;
import java.nio.file.Paths;
//This servlet is an interface between draw.io and CloudConverter.
//For EMF files, it detect its size and resize the huge images such that max dimension is MAX_DIM
public class ConverterServlet extends HttpServlet
{
private static final long serialVersionUID = -5084595244442555865L;
private static final Logger log = Logger
.getLogger(HttpServlet.class.getName());
private static final int MAX_DIM = 5000;
private static final int MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
private static final double EMF_10thMM2PXL = 26.458;
private static final String API_KEY_FILE_PATH = "/WEB-INF/cloud_convert_api_key"; // Not migrated to new pattern, since will not be used on diagrams.net
private static final String CONVERT_SERVICE_URL = "https://api.cloudconvert.com/convert";
private static final String CRLF = "\r\n";
private static final String TWO_HYPHENS = "--";
private static final String BOUNDARY = "----WebKitFormBoundary6XTanBMjO0kFwa3p"; //FIXME The boundary should not occur inside the file, it is very unlikely but still a possibility
private static String API_KEY = null;
private void readApiKey()
{
if (API_KEY == null)
{
try
{
API_KEY = Utils
.readInputStream(getServletContext()
.getResourceAsStream(API_KEY_FILE_PATH))
.replaceAll("\n", "");
}
catch (IOException e)
{
throw new RuntimeException("Invalid API key file/path");
}
}
}
//Little-endian
private int fromByteArray(byte[] bytes, int start)
{
return ((bytes[start + 3] & 0xFF) << 24) |
((bytes[start + 2] & 0xFF) << 16) |
((bytes[start + 1] & 0xFF) << 8 ) |
((bytes[start] & 0xFF) << 0 );
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
readApiKey();
String inputformat = null, outputformat = null, fileName = null;
InputStream fileContent = null;
try
{
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items)
{
if (item.isFormField())
{
String fieldName = item.getFieldName();
if ("inputformat".equals(fieldName))
{
inputformat = item.getString();
}
else if ("outputformat".equals(fieldName))
{
outputformat = item.getString();
}
}
else
{
//We expect only one file
Path file = Paths.get(item.getName());
fileName = file.getFileName().toString();
fileContent = item.getInputStream();
}
}
}
catch (FileUploadException e)
{
throw new ServletException("Cannot parse multipart request.", e);
}
if (inputformat == null || outputformat == null || fileContent == null)
{
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
else
{
HttpURLConnection con = null;
try
{
URL obj = new URL(CONVERT_SERVICE_URL);
con = (HttpURLConnection) obj.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
DataOutputStream postRequest = new DataOutputStream(con.getOutputStream());
byte[] data = new byte[10240]; //10 KB buffer
int bytesRead = fileContent.read(data);
int w = 0, h = 0, dpi = 96;
if (inputformat.equals("emf") && bytesRead >= 40)
{
//Read Frame from EMF header (the rectangular inclusive-inclusive dimensions, in .01 millimeter units,
// of a rectangle that surrounds the image stored in the metafile.)
int x0 = fromByteArray(data, 24);
int y0 = fromByteArray(data, 28);
int x1 = fromByteArray(data, 32);
int y1 = fromByteArray(data, 36);
//Approximate dimensions of the image
w = (int) ((x1 - x0) / EMF_10thMM2PXL);
h = (int) ((y1 - y0) / EMF_10thMM2PXL);
}
if (w > MAX_DIM || h > MAX_DIM)
{
dpi = (int) (dpi * Math.min(MAX_DIM / (double) w, MAX_DIM / (double) h));
if (dpi == 0)
{
dpi = 1;
}
}
addParameter("apikey", API_KEY, postRequest);
addParameter("inputformat", inputformat, postRequest);
addParameter("outputformat", outputformat, postRequest);
addParameter("input", "upload", postRequest);
addParameter("wait", "true", postRequest);
addParameter("download", "true", postRequest);
if (dpi != 96)
{
addParameter("converteroptions[density]", Integer.toString(dpi), postRequest);
}
addParameterHeader("file", fileName, postRequest);
int total = 0;
while(bytesRead != -1)
{
postRequest.write(data, 0, bytesRead);
bytesRead = fileContent.read(data);
total += bytesRead;
if (total > Utils.MAX_SIZE)
{
postRequest.close();
throw new Exception("File size exceeds the maximum allowed size of " + MAX_FILE_SIZE + " bytes.");
}
}
postRequest.writeBytes(CRLF + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + CRLF);
postRequest.flush();
postRequest.close();
InputStream in = con.getInputStream();
response.setStatus(con.getResponseCode());
String contentType = "application/octet-stream";
if ("png".equals(outputformat))
{
contentType = "image/png";
}
else if ("jpg".equals(outputformat))
{
contentType = "image/jpeg";
}
response.setHeader("Content-Type", contentType);
OutputStream out = response.getOutputStream();
bytesRead = in.read(data);
try
{
URI uri = new URI(request.getHeader("referer"));
String domain = uri.getHost();
log.log(Level.CONFIG, "EMF-CONVERT, domain: " + domain + " ,Filename: " +
fileName != null ? fileName : "" + ", size: " + bytesRead);
}
catch (Exception e)
{
e.printStackTrace();
}
while(bytesRead != -1)
{
out.write(data, 0, bytesRead);
bytesRead = in.read(data);
}
in.close();
out.flush();
out.close();
}
catch(Exception e)
{
e.printStackTrace();
if (con != null)
{
try
{
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getErrorStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.err.println(inputLine);
}
in.close();
}
catch (Exception e2)
{
// Ignore
}
}
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
}
private void addParameter(String name, String val, DataOutputStream postRequest) throws IOException {
addParameterHeader(name, null, postRequest);
postRequest.writeBytes(val);
postRequest.writeBytes(CRLF);
}
private void addParameterHeader(String name, String fileName, DataOutputStream postRequest) throws IOException {
postRequest.writeBytes(TWO_HYPHENS + BOUNDARY + CRLF);
postRequest.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" +
(fileName != null? "; filename=\"" + fileName + "\"" + CRLF + "Content-Type: application/octet-stream" : "") + CRLF);
postRequest.writeBytes(CRLF);
}
}
| jgraph/drawio | src/main/java/com/mxgraph/online/ConverterServlet.java |
45,336 | /*
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2012/03/03 Moved popups to stdmenus extension
// ZAP: 2012/04/23 Added @Override annotation to all appropriate methods.
// ZAP: 2012/10/17 Issue 393: Added more online links from menu
// ZAP: 2013/01/23 Clean up of exception handling/logging.
// ZAP: 2013/03/03 Issue 547: Deprecate unused classes and methods
// ZAP: 2013/04/16 Issue 638: Persist and snapshot sessions instead of saving them
// ZAP: 2013/09/11 Issue 786: Snapshot session menu item not working
// ZAP: 2014/01/28 Issue 207: Support keyboard shortcuts
// ZAP: 2014/11/11 Issue 1406: Move online menu items to an add-on
// ZAP: 2014/12/22 Issue 1476: Display contexts in the Sites tree
// ZAP: 2015/02/05 Issue 1524: New Persist Session dialog
// ZAP: 2017/05/10 Issue 3460: Add Show Support Info help menuitem
// ZAP: 2017/06/27 Issue 2375: Added option to change ZAP mode in edit menu
// ZAP: 2017/09/02 Use KeyEvent instead of Event (deprecated in Java 9).
// ZAP: 2018/07/17 Use ViewDelegate.getMenuShortcutKeyStroke.
// ZAP: 2019/03/15 Issue 3578: Added new menu Import
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
// ZAP: 2020/06/07 JavaDoc corrections.
// ZAP: 2020/11/26 Use Log4j 2 classes for logging.
// ZAP: 2021/04/08 Remove/fix boilerplate javadocs, and un-necessary fully qualified method return
// types.
// ZAP: 2021/05/14 Remove redundant type arguments.
// ZAP: 2021/12/30 Disable snapshot menu item if session not already persisted, add tooltip to
// disabled menu item (Issue 6938).
// ZAP: 2022/03/12 Add open recent menu
// ZAP: 2022/08/05 Address warns with Java 18 (Issue 7389).
// ZAP: 2023/01/10 Tidy up logger.
package org.parosproxy.paros.view;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.control.Control.Mode;
import org.parosproxy.paros.control.MenuFileControl;
import org.parosproxy.paros.control.MenuToolsControl;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.Session;
import org.zaproxy.zap.view.AboutDialog;
import org.zaproxy.zap.view.ZapMenuItem;
import org.zaproxy.zap.view.ZapSortedMenu;
import org.zaproxy.zap.view.ZapSupportDialog;
@SuppressWarnings("serial")
public class MainMenuBar extends JMenuBar {
private static final long serialVersionUID = 8580116506279095244L;
private static final Logger LOGGER = LogManager.getLogger(MainMenuBar.class);
private javax.swing.JMenu menuEdit = null;
private javax.swing.JMenu menuTools = null;
private javax.swing.JMenu menuView = null;
private javax.swing.JMenu menuImport = null;
private ZapMenuItem menuToolsOptions = null;
private javax.swing.JMenu menuFile = null;
private JMenu menuFileOpenRecent;
private ZapMenuItem menuFileNewSession = null;
private ZapMenuItem menuFileOpen = null;
private ZapMenuItem menuFileSaveAs = null;
private ZapMenuItem menuFileSnapshot = null;
private ZapMenuItem menuFileContextExport = null;
private ZapMenuItem menuFileContextImport = null;
private ZapMenuItem menuFileExit = null;
private ZapMenuItem menuFileExitAndDelete = null;
private ZapMenuItem menuFileProperties = null;
private JMenu menuHelp = null;
private ZapMenuItem menuHelpAbout = null;
private ZapMenuItem menuHelpSupport = null;
private JMenu menuAnalyse = null;
private JMenu menuZapMode = null;
private ButtonGroup menuZapModeGroup = null;
private Map<Mode, JRadioButtonMenuItem> menuZapModeMap = null;
// ZAP: Added standard report menu
private JMenu menuReport = null;
private JMenu menuOnline = null;
public MainMenuBar() {
super();
initialize();
}
private void initialize() {
this.add(getMenuFile());
this.add(getMenuEdit());
this.add(getMenuView());
this.add(getMenuAnalyse());
this.add(getMenuReport());
this.add(getMenuTools());
this.add(getMenuImport());
this.add(getMenuOnline());
this.add(getMenuHelp());
}
/**
* Gets the Edit menu
*
* @return the Edit menu
*/
public javax.swing.JMenu getMenuEdit() {
if (menuEdit == null) {
menuEdit = new javax.swing.JMenu();
menuEdit.setText(Constant.messages.getString("menu.edit")); // ZAP: i18n
menuEdit.setMnemonic(Constant.messages.getChar("menu.edit.mnemonic"));
menuEdit.add(getMenuEditZAPMode());
menuEdit.addSeparator();
}
return menuEdit;
}
private JMenuItem getMenuEditZAPMode() {
if (menuZapMode == null) {
menuZapMode = new JMenu(Constant.messages.getString("menu.edit.zapmode"));
menuZapModeGroup = new ButtonGroup();
JRadioButtonMenuItem newButton;
menuZapModeMap = new HashMap<>();
for (Mode modeType : Mode.values()) {
newButton = addZAPModeMenuItem(modeType);
menuZapModeGroup.add(newButton);
menuZapMode.add(newButton);
menuZapModeMap.put(modeType, newButton);
}
Mode mode =
Mode.valueOf(Model.getSingleton().getOptionsParam().getViewParam().getMode());
setMode(mode);
}
return menuZapMode;
}
private JRadioButtonMenuItem addZAPModeMenuItem(final Mode modeType) {
final JRadioButtonMenuItem modeItem =
new JRadioButtonMenuItem(
Constant.messages.getString(
"view.toolbar.mode." + modeType.name() + ".select"));
modeItem.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
Control.getSingleton().setMode(modeType);
View.getSingleton().getMainFrame().getMainToolbarPanel().setMode(modeType);
}
});
return modeItem;
}
public void setMode(final Mode mode) {
SwingUtilities.invokeLater(
new Runnable() {
@Override
public void run() {
menuZapModeMap.get(mode).setSelected(true);
}
});
}
/**
* Gets the Tools menu
*
* @return the Tools menu
*/
public JMenu getMenuTools() {
if (menuTools == null) {
menuTools = new javax.swing.JMenu();
menuTools.setText(Constant.messages.getString("menu.tools")); // ZAP: i18n
menuTools.setMnemonic(Constant.messages.getChar("menu.tools.mnemonic"));
menuTools.addSeparator();
menuTools.add(getMenuToolsOptions());
}
return menuTools;
}
/**
* Gets the View menu
*
* @return the View menu
*/
public JMenu getMenuView() {
if (menuView == null) {
menuView = new javax.swing.JMenu();
menuView.setText(Constant.messages.getString("menu.view")); // ZAP: i18n
menuView.setMnemonic(Constant.messages.getChar("menu.view.mnemonic"));
}
return menuView;
}
/**
* Gets the Import menu
*
* @return the Import menu
* @since 2.8.0
*/
public JMenu getMenuImport() {
if (menuImport == null) {
menuImport = new ZapSortedMenu();
menuImport.setText(Constant.messages.getString("menu.import"));
menuImport.setMnemonic(Constant.messages.getChar("menu.import.mnemonic"));
}
return menuImport;
}
private ZapMenuItem getMenuToolsOptions() {
if (menuToolsOptions == null) {
menuToolsOptions =
new ZapMenuItem(
"menu.tools.options",
View.getSingleton()
.getMenuShortcutKeyStroke(
KeyEvent.VK_O, KeyEvent.ALT_DOWN_MASK, false));
menuToolsOptions.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
getMenuToolsControl().options();
}
});
}
return menuToolsOptions;
}
/**
* Gets the File menu
*
* @return the File menu
*/
public JMenu getMenuFile() {
if (menuFile == null) {
menuFile = new javax.swing.JMenu();
menuFile.setText(Constant.messages.getString("menu.file")); // ZAP: i18n
menuFile.setMnemonic(Constant.messages.getChar("menu.file.mnemonic"));
menuFile.add(getMenuFileNewSession());
menuFile.add(getMenuFileOpen());
menuFile.add(getMenuFileOpenRecent());
menuFile.addSeparator();
menuFile.add(getMenuFileSaveAs());
menuFile.add(getMenuFileSnapshot());
menuFile.addSeparator();
menuFile.add(getMenuFileProperties());
menuFile.addSeparator();
menuFile.add(getMenuContextImport());
menuFile.add(getMenuContextExport());
menuFile.addSeparator();
menuFile.add(getMenuFileExitAndDelete());
menuFile.add(getMenuFileExit());
}
return menuFile;
}
private JMenuItem getMenuFileNewSession() {
if (menuFileNewSession == null) {
menuFileNewSession =
new ZapMenuItem(
"menu.file.newSession",
View.getSingleton().getMenuShortcutKeyStroke(KeyEvent.VK_N, 0, false));
menuFileNewSession.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
getMenuFileControl().newSession(true);
} catch (Exception e1) {
View.getSingleton()
.showWarningDialog(
Constant.messages.getString(
"menu.file.newSession.error")); // ZAP: i18n
LOGGER.error(e1.getMessage(), e1);
}
}
});
}
return menuFileNewSession;
}
private JMenuItem getMenuFileOpen() {
if (menuFileOpen == null) {
menuFileOpen =
new ZapMenuItem(
"menu.file.openSession",
View.getSingleton().getMenuShortcutKeyStroke(KeyEvent.VK_O, 0, false));
menuFileOpen.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
getMenuFileControl().openSession();
}
});
}
return menuFileOpen;
}
private JMenu getMenuFileOpenRecent() {
if (menuFileOpenRecent == null) {
menuFileOpenRecent = new JMenu();
menuFileOpenRecent.setText(Constant.messages.getString("menu.file.openRecent"));
refreshMenuFileOpenRecent();
}
return menuFileOpenRecent;
}
private void refreshMenuFileOpenRecent() {
menuFileOpenRecent.removeAll();
for (String session :
Model.getSingleton().getOptionsParam().getViewParam().getRecentSessions()) {
JMenuItem menuItem = new JMenuItem(session);
menuItem.addActionListener(e -> getMenuFileControl().openSession(session));
menuFileOpenRecent.add(menuItem);
}
menuFileOpenRecent.setEnabled(menuFileOpenRecent.getMenuComponentCount() != 0);
}
private JMenuItem getMenuFileSaveAs() {
if (menuFileSaveAs == null) {
menuFileSaveAs = new ZapMenuItem("menu.file.persistSession");
menuFileSaveAs.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
if (Model.getSingleton().getSession().isNewState()) {
getMenuFileControl().saveAsSession();
} else {
View.getSingleton()
.showWarningDialog(
Constant.messages.getString(
"menu.file.sessionExists.error"));
}
}
});
}
return menuFileSaveAs;
}
private JMenuItem getMenuFileSnapshot() {
if (menuFileSnapshot == null) {
menuFileSnapshot = new ZapMenuItem("menu.file.snapshotSession");
menuFileSnapshot.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
if (!Model.getSingleton().getSession().isNewState()) {
getMenuFileControl().saveSnapshot();
} else {
View.getSingleton()
.showWarningDialog(
Constant.messages.getString(
"menu.file.snapshotSession.error"));
}
}
});
toggleSnapshotState(false);
}
return menuFileSnapshot;
}
private JMenuItem getMenuFileExit() {
if (menuFileExit == null) {
menuFileExit = new ZapMenuItem("menu.file.exit");
menuFileExit.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
getMenuFileControl().exit();
}
});
}
return menuFileExit;
}
private javax.swing.JMenuItem getMenuFileExitAndDelete() {
if (menuFileExitAndDelete == null) {
menuFileExitAndDelete = new ZapMenuItem("menu.file.exit.delete");
menuFileExitAndDelete.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
int ans =
View.getSingleton()
.showConfirmDialog(
Constant.messages.getString(
"menu.file.exit.delete.warning"));
if (ans == JOptionPane.OK_OPTION) {
Control.getSingleton()
.exitAndDeleteSession(
Model.getSingleton().getSession().getFileName());
}
}
});
}
return menuFileExitAndDelete;
}
/**
* Gets the File Menu Control
*
* @return the File Menu Control
*/
public MenuFileControl getMenuFileControl() {
return Control.getSingleton().getMenuFileControl();
}
private MenuToolsControl getMenuToolsControl() {
return Control.getSingleton().getMenuToolsControl();
}
private ZapMenuItem getMenuFileProperties() {
if (menuFileProperties == null) {
menuFileProperties =
new ZapMenuItem(
"menu.file.properties",
View.getSingleton()
.getMenuShortcutKeyStroke(
KeyEvent.VK_P, KeyEvent.ALT_DOWN_MASK, false));
menuFileProperties.setText(
Constant.messages.getString("menu.file.properties")); // ZAP: i18n
menuFileProperties.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
getMenuFileControl().properties();
}
});
}
return menuFileProperties;
}
private ZapMenuItem getMenuContextImport() {
if (menuFileContextImport == null) {
menuFileContextImport = new ZapMenuItem("menu.file.context.import");
menuFileContextImport.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
getMenuFileControl().importContext();
}
});
}
return menuFileContextImport;
}
private ZapMenuItem getMenuContextExport() {
if (menuFileContextExport == null) {
menuFileContextExport = new ZapMenuItem("menu.file.context.export");
menuFileContextExport.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
getMenuFileControl().exportContext();
}
});
}
return menuFileContextExport;
}
/**
* Gets the Help menu
*
* @return the Help menu
*/
public JMenu getMenuHelp() {
if (menuHelp == null) {
menuHelp = new JMenu();
menuHelp.setText(Constant.messages.getString("menu.help")); // ZAP: i18n
menuHelp.setMnemonic(Constant.messages.getChar("menu.help.mnemonic"));
menuHelp.add(getMenuHelpAbout());
menuHelp.add(getMenuHelpSupport());
}
return menuHelp;
}
public JMenu getMenuOnline() {
if (menuOnline == null) {
menuOnline = new JMenu();
menuOnline.setText(Constant.messages.getString("menu.online"));
menuOnline.setMnemonic(Constant.messages.getChar("menu.online.mnemonic"));
}
return menuOnline;
}
// ZAP: Added standard report menu
public JMenu getMenuReport() {
if (menuReport == null) {
menuReport = new JMenu();
menuReport.setText(Constant.messages.getString("menu.report")); // ZAP: i18n
menuReport.setMnemonic(Constant.messages.getChar("menu.report.mnemonic"));
}
return menuReport;
}
/**
* Gets the About menu
*
* @return the 'About' menu item.
*/
private ZapMenuItem getMenuHelpAbout() {
if (menuHelpAbout == null) {
menuHelpAbout = new ZapMenuItem("menu.help.about");
menuHelpAbout.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
AboutDialog dialog =
new AboutDialog(View.getSingleton().getMainFrame(), true);
dialog.setVisible(true);
}
});
}
return menuHelpAbout;
}
private ZapMenuItem getMenuHelpSupport() {
if (menuHelpSupport == null) {
menuHelpSupport = new ZapMenuItem("menu.help.zap.support");
menuHelpSupport.addActionListener(
new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent e) {
ZapSupportDialog zsd =
new ZapSupportDialog(View.getSingleton().getMainFrame(), true);
zsd.setVisible(true);
}
});
}
return menuHelpSupport;
}
/**
* Gets the Analyze menu
*
* @return the Analyse menu
*/
public JMenu getMenuAnalyse() {
if (menuAnalyse == null) {
menuAnalyse = new JMenu();
menuAnalyse.setText(Constant.messages.getString("menu.analyse")); // ZAP: i18n
menuAnalyse.setMnemonic(Constant.messages.getChar("menu.analyse.mnemonic"));
}
return menuAnalyse;
}
public void sessionChanged(Session session) {
if (session != null) {
this.getMenuFileSaveAs().setEnabled(session.isNewState());
toggleSnapshotState(!session.isNewState());
refreshMenuFileOpenRecent();
}
}
private void toggleSnapshotState(boolean enabled) {
if (enabled) {
menuFileSnapshot.setToolTipText("");
} else {
menuFileSnapshot.setToolTipText(
Constant.messages.getString("menu.file.snapshotSession.disabled.tooltip"));
}
menuFileSnapshot.setEnabled(enabled);
}
}
| zaproxy/zaproxy | zap/src/main/java/org/parosproxy/paros/view/MainMenuBar.java |
45,337 | /*
* This file is part of Arduino.
*
* Copyright 2015 Arduino LLC (http://www.arduino.cc/)
*
* Arduino is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* As a special exception, you may use this file as part of a free software
* library without restriction. Specifically, if other files instantiate
* templates or use macros or inline functions from this file, or you compile
* this file and link it with other files to produce an executable, this
* file does not by itself cause the resulting executable to be covered by
* the GNU General Public License. This exception does not however
* invalidate any other reasons why the executable file might be covered by
* the GNU General Public License.
*/
package cc.arduino.contributions.packages;
public class ContributedHelp {
private String online;
public String getOnline() { return online; }
}
| maxbbraun/Arduino | arduino-core/src/cc/arduino/contributions/packages/ContributedHelp.java |
45,338 | package me.chanjar.weixin.mp.api.impl;
import com.google.gson.JsonObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor;
import me.chanjar.weixin.mp.api.WxMpKefuService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfAccountRequest;
import me.chanjar.weixin.mp.bean.kefu.request.WxMpKfSessionRequest;
import me.chanjar.weixin.mp.bean.kefu.result.*;
import java.io.File;
import java.util.Date;
import static me.chanjar.weixin.mp.enums.WxMpApiUrl.Kefu.*;
/**
* @author Binary Wang
*/
@Slf4j
@RequiredArgsConstructor
public class WxMpKefuServiceImpl implements WxMpKefuService {
private final WxMpService wxMpService;
@Override
public boolean sendKefuMessage(WxMpKefuMessage message) throws WxErrorException {
return this.sendKefuMessageWithResponse(message) != null;
}
@Override
public String sendKefuMessageWithResponse(WxMpKefuMessage message) throws WxErrorException {
return this.wxMpService.post(MESSAGE_CUSTOM_SEND, message.toJson());
}
@Override
public WxMpKfList kfList() throws WxErrorException {
String responseContent = this.wxMpService.get(GET_KF_LIST, null);
return WxMpKfList.fromJson(responseContent);
}
@Override
public WxMpKfOnlineList kfOnlineList() throws WxErrorException {
String responseContent = this.wxMpService.get(GET_ONLINE_KF_LIST, null);
return WxMpKfOnlineList.fromJson(responseContent);
}
@Override
public boolean kfAccountAdd(WxMpKfAccountRequest request) throws WxErrorException {
String responseContent = this.wxMpService.post(KFACCOUNT_ADD, request.toJson());
return responseContent != null;
}
@Override
public boolean kfAccountUpdate(WxMpKfAccountRequest request) throws WxErrorException {
String responseContent = this.wxMpService.post(KFACCOUNT_UPDATE, request.toJson());
return responseContent != null;
}
@Override
public boolean kfAccountInviteWorker(WxMpKfAccountRequest request) throws WxErrorException {
String responseContent = this.wxMpService.post(KFACCOUNT_INVITE_WORKER, request.toJson());
return responseContent != null;
}
@Override
public boolean kfAccountUploadHeadImg(String kfAccount, File imgFile) throws WxErrorException {
WxMediaUploadResult responseContent = this.wxMpService
.execute(MediaUploadRequestExecutor.create(this.wxMpService.getRequestHttp()),
String.format(KFACCOUNT_UPLOAD_HEAD_IMG.getUrl(this.wxMpService.getWxMpConfigStorage()), kfAccount), imgFile);
return responseContent != null;
}
@Override
public boolean kfAccountDel(String kfAccount) throws WxErrorException {
String responseContent = this.wxMpService.get(String.format(KFACCOUNT_DEL.getUrl(this.wxMpService.getWxMpConfigStorage()),
kfAccount), null);
return responseContent != null;
}
@Override
public boolean kfSessionCreate(String openid, String kfAccount) throws WxErrorException {
WxMpKfSessionRequest request = new WxMpKfSessionRequest(kfAccount, openid);
String responseContent = this.wxMpService.post(KFSESSION_CREATE, request.toJson());
return responseContent != null;
}
@Override
public boolean kfSessionClose(String openid, String kfAccount) throws WxErrorException {
WxMpKfSessionRequest request = new WxMpKfSessionRequest(kfAccount, openid);
String responseContent = this.wxMpService.post(KFSESSION_CLOSE, request.toJson());
return responseContent != null;
}
@Override
public WxMpKfSessionGetResult kfSessionGet(String openid) throws WxErrorException {
String responseContent = this.wxMpService.get(String.format(KFSESSION_GET_SESSION
.getUrl(this.wxMpService.getWxMpConfigStorage()), openid), null);
return WxMpKfSessionGetResult.fromJson(responseContent);
}
@Override
public WxMpKfSessionList kfSessionList(String kfAccount) throws WxErrorException {
String responseContent = this.wxMpService.get(String.format(KFSESSION_GET_SESSION_LIST
.getUrl(this.wxMpService.getWxMpConfigStorage()), kfAccount), null);
return WxMpKfSessionList.fromJson(responseContent);
}
@Override
public WxMpKfSessionWaitCaseList kfSessionGetWaitCase() throws WxErrorException {
String responseContent = this.wxMpService.get(KFSESSION_GET_WAIT_CASE, null);
return WxMpKfSessionWaitCaseList.fromJson(responseContent);
}
@Override
public WxMpKfMsgList kfMsgList(Date startTime, Date endTime, Long msgId, Integer number) throws WxErrorException {
if (number > 10000) {
throw new WxErrorException("非法参数请求,每次最多查询10000条记录!");
}
if (startTime.after(endTime)) {
throw new WxErrorException("起始时间不能晚于结束时间!");
}
JsonObject param = new JsonObject();
param.addProperty("starttime", startTime.getTime() / 1000);
param.addProperty("endtime", endTime.getTime() / 1000);
param.addProperty("msgid", msgId);
param.addProperty("number", number);
String responseContent = this.wxMpService.post(MSG_RECORD_LIST, param.toString());
return WxMpKfMsgList.fromJson(responseContent);
}
@Override
public WxMpKfMsgList kfMsgList(Date startTime, Date endTime) throws WxErrorException {
int number = 10000;
WxMpKfMsgList result = this.kfMsgList(startTime, endTime, 1L, number);
if (result != null && result.getNumber() == number) {
Long msgId = result.getMsgId();
WxMpKfMsgList followingResult = this.kfMsgList(startTime, endTime, msgId, number);
while (followingResult != null && followingResult.getRecords().size() > 0) {
result.getRecords().addAll(followingResult.getRecords());
result.setNumber(result.getNumber() + followingResult.getNumber());
result.setMsgId(followingResult.getMsgId());
followingResult = this.kfMsgList(startTime, endTime, followingResult.getMsgId(), number);
}
}
return result;
}
@Override
public boolean sendKfTypingState(String openid, String command) throws WxErrorException {
JsonObject params = new JsonObject();
params.addProperty("touser", openid);
params.addProperty("command", command);
String responseContent = this.wxMpService.post(CUSTOM_TYPING, params.toString());
return responseContent != null;
}
}
| Wechat-Group/WxJava | weixin-java-mp/src/main/java/me/chanjar/weixin/mp/api/impl/WxMpKefuServiceImpl.java |
45,339 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Components;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.FrameLayout;
import android.widget.ImageView;
import androidx.core.content.ContextCompat;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ApplicationLoader;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.DialogObject;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.ImageLoader;
import org.telegram.messenger.ImageReceiver;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarPopupWindow;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.SimpleTextView;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Business.BusinessLinksController;
import org.telegram.ui.ChatActivity;
import org.telegram.ui.ProfileActivity;
import org.telegram.ui.Stories.StoriesUtilities;
import org.telegram.ui.TopicsFragment;
import java.util.concurrent.atomic.AtomicReference;
public class ChatAvatarContainer extends FrameLayout implements NotificationCenter.NotificationCenterDelegate {
public boolean allowDrawStories;
private Integer storiesForceState;
public BackupImageView avatarImageView;
private SimpleTextView titleTextView;
private AtomicReference<SimpleTextView> titleTextLargerCopyView = new AtomicReference<>();
private SimpleTextView subtitleTextView;
private AnimatedTextView animatedSubtitleTextView;
private AtomicReference<SimpleTextView> subtitleTextLargerCopyView = new AtomicReference<>();
private ImageView timeItem;
private TimerDrawable timerDrawable;
private ChatActivity parentFragment;
private StatusDrawable[] statusDrawables = new StatusDrawable[6];
private AvatarDrawable avatarDrawable = new AvatarDrawable();
private int currentAccount = UserConfig.selectedAccount;
private boolean occupyStatusBar = true;
private int leftPadding = AndroidUtilities.dp(8);
private int rightAvatarPadding = 0;
StatusDrawable currentTypingDrawable;
private int lastWidth = -1;
private int largerWidth = -1;
private AnimatorSet titleAnimation;
private boolean[] isOnline = new boolean[1];
public boolean[] statusMadeShorter = new boolean[1];
private boolean secretChatTimer;
private int onlineCount = -1;
private int currentConnectionState;
private CharSequence lastSubtitle;
private int lastSubtitleColorKey = -1;
private Integer overrideSubtitleColor;
private SharedMediaLayout.SharedMediaPreloader sharedMediaPreloader;
private Theme.ResourcesProvider resourcesProvider;
public boolean allowShorterStatus = false;
public boolean premiumIconHiddable = false;
private AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable emojiStatusDrawable;
protected boolean useAnimatedSubtitle() {
return false;
}
public void hideSubtitle() {
if (getSubtitleTextView() != null) {
getSubtitleTextView().setVisibility(View.GONE);
}
}
public void setStoriesForceState(Integer storiesForceState) {
this.storiesForceState = storiesForceState;
}
private class SimpleTextConnectedView extends SimpleTextView {
private AtomicReference<SimpleTextView> reference;
public SimpleTextConnectedView(Context context, AtomicReference<SimpleTextView> reference) {
super(context);
this.reference = reference;
}
@Override
public void setTranslationY(float translationY) {
if (reference != null) {
SimpleTextView connected = reference.get();
if (connected != null) {
connected.setTranslationY(translationY);
}
}
super.setTranslationY(translationY);
}
@Override
public boolean setText(CharSequence value) {
if (reference != null) {
SimpleTextView connected = reference.get();
if (connected != null) {
connected.setText(value);
}
}
return super.setText(value);
}
}
public ChatAvatarContainer(Context context, BaseFragment baseFragment, boolean needTime) {
this(context, baseFragment, needTime, null);
}
public ChatAvatarContainer(Context context, BaseFragment baseFragment, boolean needTime, Theme.ResourcesProvider resourcesProvider) {
super(context);
this.resourcesProvider = resourcesProvider;
if (baseFragment instanceof ChatActivity) {
parentFragment = (ChatActivity) baseFragment;
}
final boolean avatarClickable = parentFragment != null && parentFragment.getChatMode() == 0 && !UserObject.isReplyUser(parentFragment.getCurrentUser());
avatarImageView = new BackupImageView(context) {
StoriesUtilities.AvatarStoryParams params = new StoriesUtilities.AvatarStoryParams(true) {
@Override
public void openStory(long dialogId, Runnable onDone) {
baseFragment.getOrCreateStoryViewer().open(getContext(), dialogId, (dialogId1, messageId, storyId, type, holder) -> {
holder.crossfadeToAvatarImage = holder.storyImage = imageReceiver;
holder.params = params;
holder.view = avatarImageView;
holder.alpha = avatarImageView.getAlpha();
holder.clipTop = 0;
holder.clipBottom = AndroidUtilities.displaySize.y;
holder.clipParent = (View) getParent();
return true;
});
}
};
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
if (avatarClickable && getImageReceiver().hasNotThumb()) {
info.setText(LocaleController.getString("AccDescrProfilePicture", R.string.AccDescrProfilePicture));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
info.addAction(new AccessibilityNodeInfo.AccessibilityAction(AccessibilityNodeInfo.ACTION_CLICK, LocaleController.getString("Open", R.string.Open)));
}
} else {
info.setVisibleToUser(false);
}
}
@Override
protected void onDraw(Canvas canvas) {
if (allowDrawStories && animatedEmojiDrawable == null) {
params.originalAvatarRect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
params.drawSegments = true;
params.drawInside = true;
params.resourcesProvider = resourcesProvider;
if (storiesForceState != null) {
params.forceState = storiesForceState;
}
long dialogId = 0;
if (parentFragment != null) {
dialogId = parentFragment.getDialogId();
} else if (baseFragment instanceof TopicsFragment) {
dialogId = ((TopicsFragment) baseFragment).getDialogId();
}
StoriesUtilities.drawAvatarWithStory(dialogId, canvas, imageReceiver, params);
} else {
super.onDraw(canvas);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (allowDrawStories) {
if (params.checkOnTouchEvent(event, this)) {
return true;
}
}
return super.onTouchEvent(event);
}
};
if (baseFragment instanceof ChatActivity || baseFragment instanceof TopicsFragment) {
if (parentFragment == null || (parentFragment.getChatMode() != ChatActivity.MODE_QUICK_REPLIES && parentFragment.getChatMode() != ChatActivity.MODE_EDIT_BUSINESS_LINK)) {
sharedMediaPreloader = new SharedMediaLayout.SharedMediaPreloader(baseFragment);
}
if (parentFragment != null && (parentFragment.isThreadChat() || parentFragment.getChatMode() == ChatActivity.MODE_PINNED || parentFragment.getChatMode() == ChatActivity.MODE_QUICK_REPLIES || parentFragment.getChatMode() == ChatActivity.MODE_EDIT_BUSINESS_LINK)) {
avatarImageView.setVisibility(GONE);
}
}
avatarImageView.setContentDescription(LocaleController.getString("AccDescrProfilePicture", R.string.AccDescrProfilePicture));
avatarImageView.setRoundRadius(AndroidUtilities.dp(21));
addView(avatarImageView);
if (avatarClickable) {
avatarImageView.setOnClickListener(v -> {
if (!onAvatarClick()) {
openProfile(true);
}
});
}
titleTextView = new SimpleTextConnectedView(context, titleTextLargerCopyView);
titleTextView.setEllipsizeByGradient(true);
titleTextView.setTextColor(getThemedColor(Theme.key_actionBarDefaultTitle));
titleTextView.setTextSize(18);
titleTextView.setGravity(Gravity.LEFT);
titleTextView.setTypeface(AndroidUtilities.getTypeface(AndroidUtilities.TYPEFACE_ROBOTO_MEDIUM));
titleTextView.setLeftDrawableTopPadding(-AndroidUtilities.dp(1.3f));
titleTextView.setCanHideRightDrawable(false);
titleTextView.setRightDrawableOutside(true);
titleTextView.setPadding(0, AndroidUtilities.dp(6), 0, AndroidUtilities.dp(12));
addView(titleTextView);
if (useAnimatedSubtitle()) {
animatedSubtitleTextView = new AnimatedTextView(context, true, true, true);
animatedSubtitleTextView.setAnimationProperties(.3f, 0, 320, CubicBezierInterpolator.EASE_OUT_QUINT);
animatedSubtitleTextView.setEllipsizeByGradient(true);
animatedSubtitleTextView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubtitle));
animatedSubtitleTextView.setTag(Theme.key_actionBarDefaultSubtitle);
animatedSubtitleTextView.setTextSize(AndroidUtilities.dp(14));
animatedSubtitleTextView.setGravity(Gravity.LEFT);
animatedSubtitleTextView.setPadding(0, 0, AndroidUtilities.dp(10), 0);
animatedSubtitleTextView.setTranslationY(-AndroidUtilities.dp(1));
addView(animatedSubtitleTextView);
} else {
subtitleTextView = new SimpleTextConnectedView(context, subtitleTextLargerCopyView);
subtitleTextView.setEllipsizeByGradient(true);
subtitleTextView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubtitle));
subtitleTextView.setTag(Theme.key_actionBarDefaultSubtitle);
subtitleTextView.setTextSize(14);
subtitleTextView.setGravity(Gravity.LEFT);
subtitleTextView.setPadding(0, 0, AndroidUtilities.dp(10), 0);
addView(subtitleTextView);
}
if (parentFragment != null) {
timeItem = new ImageView(context);
timeItem.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(10), AndroidUtilities.dp(5), AndroidUtilities.dp(5));
timeItem.setScaleType(ImageView.ScaleType.CENTER);
timeItem.setAlpha(0.0f);
timeItem.setScaleY(0.0f);
timeItem.setScaleX(0.0f);
timeItem.setVisibility(GONE);
timeItem.setImageDrawable(timerDrawable = new TimerDrawable(context, resourcesProvider));
addView(timeItem);
secretChatTimer = needTime;
timeItem.setOnClickListener(v -> {
if (secretChatTimer) {
parentFragment.showDialog(AlertsCreator.createTTLAlert(getContext(), parentFragment.getCurrentEncryptedChat(), resourcesProvider).create());
} else {
openSetTimer();
}
});
if (secretChatTimer) {
timeItem.setContentDescription(LocaleController.getString("SetTimer", R.string.SetTimer));
} else {
timeItem.setContentDescription(LocaleController.getString("AccAutoDeleteTimer", R.string.AccAutoDeleteTimer));
}
}
if (parentFragment != null && (parentFragment.getChatMode() == 0 || parentFragment.getChatMode() == ChatActivity.MODE_SAVED)) {
if ((!parentFragment.isThreadChat() || parentFragment.isTopic) && !UserObject.isReplyUser(parentFragment.getCurrentUser())) {
setOnClickListener(v -> openProfile(false));
}
TLRPC.Chat chat = parentFragment.getCurrentChat();
statusDrawables[0] = new TypingDotsDrawable(true);
statusDrawables[1] = new RecordStatusDrawable(true);
statusDrawables[2] = new SendingFileDrawable(true);
statusDrawables[3] = new PlayingGameDrawable(false, resourcesProvider);
statusDrawables[4] = new RoundStatusDrawable(true);
statusDrawables[5] = new ChoosingStickerStatusDrawable(true);
for (int a = 0; a < statusDrawables.length; a++) {
statusDrawables[a].setIsChat(chat != null);
}
}
emojiStatusDrawable = new AnimatedEmojiDrawable.SwapAnimatedEmojiDrawable(titleTextView, AndroidUtilities.dp(24));
}
private ButtonBounce bounce = new ButtonBounce(this);
private Runnable onLongClick = () -> {
pressed = false;
bounce.setPressed(false);
if (canSearch()) {
openSearch();
}
};
private boolean pressed;
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN && canSearch()) {
pressed = true;
bounce.setPressed(true);
AndroidUtilities.cancelRunOnUIThread(this.onLongClick);
AndroidUtilities.runOnUIThread(this.onLongClick, ViewConfiguration.getLongPressTimeout());
return true;
} else if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
if (pressed) {
bounce.setPressed(false);
pressed = false;
if (isClickable()) {
openProfile(false);
}
AndroidUtilities.cancelRunOnUIThread(this.onLongClick);
}
}
return super.onTouchEvent(ev);
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
final float s = bounce.getScale(.02f);
canvas.scale(s, s, getWidth() / 2f, getHeight() / 2f);
super.dispatchDraw(canvas);
canvas.restore();
}
protected boolean canSearch() {
return false;
}
protected void openSearch() {
}
protected boolean onAvatarClick() {
return false;
}
public void setTitleExpand(boolean titleExpand) {
int newRightPadding = titleExpand ? AndroidUtilities.dp(10) : 0;
if (titleTextView.getPaddingRight() != newRightPadding) {
titleTextView.setPadding(0, AndroidUtilities.dp(6), newRightPadding, AndroidUtilities.dp(12));
requestLayout();
invalidate();
}
}
public void setOverrideSubtitleColor(Integer overrideSubtitleColor) {
this.overrideSubtitleColor = overrideSubtitleColor;
}
public boolean openSetTimer() {
if (parentFragment.getParentActivity() == null) {
return false;
}
TLRPC.Chat chat = parentFragment.getCurrentChat();
if (chat != null && !ChatObject.canUserDoAdminAction(chat, ChatObject.ACTION_DELETE_MESSAGES)) {
if (timeItem.getTag() != null) {
parentFragment.showTimerHint();
}
return false;
}
TLRPC.ChatFull chatInfo = parentFragment.getCurrentChatInfo();
TLRPC.UserFull userInfo = parentFragment.getCurrentUserInfo();
int ttl = 0;
if (userInfo != null) {
ttl = userInfo.ttl_period;
} else if (chatInfo != null) {
ttl = chatInfo.ttl_period;
}
ActionBarPopupWindow[] scrimPopupWindow = new ActionBarPopupWindow[1];
AutoDeletePopupWrapper autoDeletePopupWrapper = new AutoDeletePopupWrapper(getContext(), null, new AutoDeletePopupWrapper.Callback() {
@Override
public void dismiss() {
if (scrimPopupWindow[0] != null) {
scrimPopupWindow[0].dismiss();
}
}
@Override
public void setAutoDeleteHistory(int time, int action) {
if (parentFragment == null) {
return;
}
parentFragment.getMessagesController().setDialogHistoryTTL(parentFragment.getDialogId(), time);
TLRPC.ChatFull chatInfo = parentFragment.getCurrentChatInfo();
TLRPC.UserFull userInfo = parentFragment.getCurrentUserInfo();
if (userInfo != null || chatInfo != null) {
UndoView undoView = parentFragment.getUndoView();
if (undoView != null) {
undoView.showWithAction(parentFragment.getDialogId(), action, parentFragment.getCurrentUser(), userInfo != null ? userInfo.ttl_period : chatInfo.ttl_period, null, null);
}
}
}
}, true, 0, resourcesProvider);
autoDeletePopupWrapper.updateItems(ttl);
scrimPopupWindow[0] = new ActionBarPopupWindow(autoDeletePopupWrapper.windowLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) {
@Override
public void dismiss() {
super.dismiss();
if (parentFragment != null) {
parentFragment.dimBehindView(false);
}
}
};
scrimPopupWindow[0].setPauseNotifications(true);
scrimPopupWindow[0].setDismissAnimationDuration(220);
scrimPopupWindow[0].setOutsideTouchable(true);
scrimPopupWindow[0].setClippingEnabled(true);
scrimPopupWindow[0].setAnimationStyle(R.style.PopupContextAnimation);
scrimPopupWindow[0].setFocusable(true);
autoDeletePopupWrapper.windowLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST));
scrimPopupWindow[0].setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
scrimPopupWindow[0].getContentView().setFocusableInTouchMode(true);
scrimPopupWindow[0].showAtLocation(avatarImageView, 0, (int) (avatarImageView.getX() + getX()), (int) avatarImageView.getY());
parentFragment.dimBehindView(true);
return true;
}
public void openProfile(boolean byAvatar) {
openProfile(byAvatar, true, false);
}
public void openProfile(boolean byAvatar, boolean fromChatAnimation, boolean removeLast) {
if (byAvatar && (AndroidUtilities.isTablet() || AndroidUtilities.displaySize.x > AndroidUtilities.displaySize.y || !avatarImageView.getImageReceiver().hasNotThumb())) {
byAvatar = false;
}
TLRPC.User user = parentFragment.getCurrentUser();
TLRPC.Chat chat = parentFragment.getCurrentChat();
ImageReceiver imageReceiver = avatarImageView.getImageReceiver();
String key = imageReceiver.getImageKey();
ImageLoader imageLoader = ImageLoader.getInstance();
if (key != null && !imageLoader.isInMemCache(key, false)) {
Drawable drawable = imageReceiver.getDrawable();
if (drawable instanceof BitmapDrawable && !(drawable instanceof AnimatedFileDrawable)) {
imageLoader.putImageToCache((BitmapDrawable) drawable, key, false);
}
}
if (user != null) {
Bundle args = new Bundle();
if (UserObject.isUserSelf(user)) {
if (!sharedMediaPreloader.hasSharedMedia()) {
return;
}
args.putLong("dialog_id", parentFragment.getDialogId());
if (parentFragment.getChatMode() == ChatActivity.MODE_SAVED) {
args.putLong("topic_id", parentFragment.getSavedDialogId());
}
MediaActivity fragment = new MediaActivity(args, sharedMediaPreloader);
fragment.setChatInfo(parentFragment.getCurrentChatInfo());
parentFragment.presentFragment(fragment, removeLast);
} else {
if (parentFragment.getChatMode() == ChatActivity.MODE_SAVED) {
long dialogId = parentFragment.getSavedDialogId();
args.putBoolean("saved", true);
if (dialogId >= 0) {
args.putLong("user_id", dialogId);
} else {
args.putLong("chat_id", -dialogId);
}
} else {
args.putLong("user_id", user.id);
if (timeItem != null) {
args.putLong("dialog_id", parentFragment.getDialogId());
}
}
args.putBoolean("reportSpam", parentFragment.hasReportSpam());
args.putInt("actionBarColor", getThemedColor(Theme.key_actionBarDefault));
ProfileActivity fragment = new ProfileActivity(args, sharedMediaPreloader);
fragment.setUserInfo(parentFragment.getCurrentUserInfo(), parentFragment.profileChannelMessageFetcher, parentFragment.birthdayAssetsFetcher);
if (fromChatAnimation) {
fragment.setPlayProfileAnimation(byAvatar ? 2 : 1);
}
parentFragment.presentFragment(fragment, removeLast);
}
} else if (chat != null) {
Bundle args = new Bundle();
args.putLong("chat_id", chat.id);
if (parentFragment.getChatMode() == ChatActivity.MODE_SAVED) {
args.putLong("topic_id", parentFragment.getSavedDialogId());
} else if (parentFragment.isTopic) {
args.putLong("topic_id", parentFragment.getThreadMessage().getId());
}
ProfileActivity fragment = new ProfileActivity(args, sharedMediaPreloader);
fragment.setChatInfo(parentFragment.getCurrentChatInfo());
if (fromChatAnimation) {
fragment.setPlayProfileAnimation(byAvatar ? 2 : 1);
}
parentFragment.presentFragment(fragment, removeLast);
}
}
public void setOccupyStatusBar(boolean value) {
occupyStatusBar = value;
}
public void setTitleColors(int title, int subtitle) {
titleTextView.setTextColor(title);
subtitleTextView.setTextColor(subtitle);
subtitleTextView.setTag(subtitle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec) + titleTextView.getPaddingRight();
int availableWidth = width - AndroidUtilities.dp((avatarImageView.getVisibility() == VISIBLE ? 54 : 0) + 16);
avatarImageView.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(42), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(42), MeasureSpec.EXACTLY));
titleTextView.measure(MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24 + 8) + titleTextView.getPaddingRight(), MeasureSpec.AT_MOST));
if (subtitleTextView != null) {
subtitleTextView.measure(MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(20), MeasureSpec.AT_MOST));
} else if (animatedSubtitleTextView != null) {
animatedSubtitleTextView.measure(MeasureSpec.makeMeasureSpec(availableWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(20), MeasureSpec.AT_MOST));
}
if (timeItem != null) {
timeItem.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(34), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(34), MeasureSpec.EXACTLY));
}
setMeasuredDimension(width, MeasureSpec.getSize(heightMeasureSpec));
if (lastWidth != -1 && lastWidth != width && lastWidth > width) {
fadeOutToLessWidth(lastWidth);
}
SimpleTextView titleTextLargerCopyView = this.titleTextLargerCopyView.get();
if (titleTextLargerCopyView != null) {
int largerAvailableWidth = largerWidth - AndroidUtilities.dp((avatarImageView.getVisibility() == VISIBLE ? 54 : 0) + 16);
titleTextLargerCopyView.measure(MeasureSpec.makeMeasureSpec(largerAvailableWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.AT_MOST));
}
lastWidth = width;
}
private void fadeOutToLessWidth(int largerWidth) {
this.largerWidth = largerWidth;
SimpleTextView titleTextLargerCopyView = this.titleTextLargerCopyView.get();
if (titleTextLargerCopyView != null) {
removeView(titleTextLargerCopyView);
}
titleTextLargerCopyView = new SimpleTextView(getContext());
this.titleTextLargerCopyView.set(titleTextLargerCopyView);
titleTextLargerCopyView.setTextColor(getThemedColor(Theme.key_actionBarDefaultTitle));
titleTextLargerCopyView.setTextSize(18);
titleTextLargerCopyView.setGravity(Gravity.LEFT);
titleTextLargerCopyView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
titleTextLargerCopyView.setLeftDrawableTopPadding(-AndroidUtilities.dp(1.3f));
titleTextLargerCopyView.setRightDrawable(titleTextView.getRightDrawable());
titleTextLargerCopyView.setRightDrawable2(titleTextView.getRightDrawable2());
titleTextLargerCopyView.setRightDrawableOutside(titleTextView.getRightDrawableOutside());
titleTextLargerCopyView.setLeftDrawable(titleTextView.getLeftDrawable());
titleTextLargerCopyView.setText(titleTextView.getText());
titleTextLargerCopyView.animate().alpha(0).setDuration(350).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).withEndAction(() -> {
SimpleTextView titleTextLargerCopyView2 = this.titleTextLargerCopyView.get();
if (titleTextLargerCopyView2 != null) {
removeView(titleTextLargerCopyView2);
this.titleTextLargerCopyView.set(null);
}
}).start();
addView(titleTextLargerCopyView);
SimpleTextView subtitleTextLargerCopyView = this.subtitleTextLargerCopyView.get();
if (subtitleTextLargerCopyView != null) {
removeView(subtitleTextLargerCopyView);
}
subtitleTextLargerCopyView = new SimpleTextView(getContext());
this.subtitleTextLargerCopyView.set(subtitleTextLargerCopyView);
subtitleTextLargerCopyView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubtitle));
subtitleTextLargerCopyView.setTag(Theme.key_actionBarDefaultSubtitle);
subtitleTextLargerCopyView.setTextSize(14);
subtitleTextLargerCopyView.setGravity(Gravity.LEFT);
if (subtitleTextView != null) {
subtitleTextLargerCopyView.setText(subtitleTextView.getText());
} else if (animatedSubtitleTextView != null) {
subtitleTextLargerCopyView.setText(animatedSubtitleTextView.getText());
}
subtitleTextLargerCopyView.animate().alpha(0).setDuration(350).setInterpolator(CubicBezierInterpolator.EASE_OUT_QUINT).withEndAction(() -> {
SimpleTextView subtitleTextLargerCopyView2 = this.subtitleTextLargerCopyView.get();
if (subtitleTextLargerCopyView2 != null) {
removeView(subtitleTextLargerCopyView2);
this.subtitleTextLargerCopyView.set(null);
if (!allowDrawStories) {
setClipChildren(true);
}
}
}).start();
addView(subtitleTextLargerCopyView);
setClipChildren(false);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
int actionBarHeight = ActionBar.getCurrentActionBarHeight();
int viewTop = (actionBarHeight - AndroidUtilities.dp(42)) / 2 + (Build.VERSION.SDK_INT >= 21 && occupyStatusBar ? AndroidUtilities.statusBarHeight : 0);
avatarImageView.layout(leftPadding, viewTop + 1, leftPadding + AndroidUtilities.dp(42), viewTop + 1 + AndroidUtilities.dp(42));
int l = leftPadding + (avatarImageView.getVisibility() == VISIBLE ? AndroidUtilities.dp( 54) : 0) + rightAvatarPadding;
SimpleTextView titleTextLargerCopyView = this.titleTextLargerCopyView.get();
if (getSubtitleTextView().getVisibility() != GONE) {
titleTextView.layout(l, viewTop + AndroidUtilities.dp(1.3f) - titleTextView.getPaddingTop(), l + titleTextView.getMeasuredWidth(), viewTop + titleTextView.getTextHeight() + AndroidUtilities.dp(1.3f) - titleTextView.getPaddingTop() + titleTextView.getPaddingBottom());
if (titleTextLargerCopyView != null) {
titleTextLargerCopyView.layout(l, viewTop + AndroidUtilities.dp(1.3f), l + titleTextLargerCopyView.getMeasuredWidth(), viewTop + titleTextLargerCopyView.getTextHeight() + AndroidUtilities.dp(1.3f));
}
} else {
titleTextView.layout(l, viewTop + AndroidUtilities.dp(11) - titleTextView.getPaddingTop(), l + titleTextView.getMeasuredWidth(), viewTop + titleTextView.getTextHeight() + AndroidUtilities.dp(11) - titleTextView.getPaddingTop() + titleTextView.getPaddingBottom());
if (titleTextLargerCopyView != null) {
titleTextLargerCopyView.layout(l, viewTop + AndroidUtilities.dp(11), l + titleTextLargerCopyView.getMeasuredWidth(), viewTop + titleTextLargerCopyView.getTextHeight() + AndroidUtilities.dp(11));
}
}
if (timeItem != null) {
timeItem.layout(leftPadding + AndroidUtilities.dp(16), viewTop + AndroidUtilities.dp(15), leftPadding + AndroidUtilities.dp(16 + 34), viewTop + AndroidUtilities.dp(15 + 34));
}
if (subtitleTextView != null) {
subtitleTextView.layout(l, viewTop + AndroidUtilities.dp(24), l + subtitleTextView.getMeasuredWidth(), viewTop + subtitleTextView.getTextHeight() + AndroidUtilities.dp(24));
} else if (animatedSubtitleTextView != null) {
animatedSubtitleTextView.layout(l, viewTop + AndroidUtilities.dp(24), l + animatedSubtitleTextView.getMeasuredWidth(), viewTop + animatedSubtitleTextView.getTextHeight() + AndroidUtilities.dp(24));
}
SimpleTextView subtitleTextLargerCopyView = this.subtitleTextLargerCopyView.get();
if (subtitleTextLargerCopyView != null) {
subtitleTextLargerCopyView.layout(l, viewTop + AndroidUtilities.dp(24), l + subtitleTextLargerCopyView.getMeasuredWidth(), viewTop + subtitleTextLargerCopyView.getTextHeight() + AndroidUtilities.dp(24));
}
}
public void setLeftPadding(int value) {
leftPadding = value;
}
public void setRightAvatarPadding(int value) {
rightAvatarPadding = value;
}
public void showTimeItem(boolean animated) {
if (timeItem == null || timeItem.getTag() != null || avatarImageView.getVisibility() != View.VISIBLE) {
return;
}
timeItem.clearAnimation();
timeItem.setVisibility(VISIBLE);
timeItem.setTag(1);
if (animated) {
timeItem.animate().setDuration(180).alpha(1.0f).scaleX(1.0f).scaleY(1.0f).setListener(null).start();
} else {
timeItem.setAlpha(1.0f);
timeItem.setScaleY(1.0f);
timeItem.setScaleX(1.0f);
}
}
public void hideTimeItem(boolean animated) {
if (timeItem == null || timeItem.getTag() == null) {
return;
}
timeItem.clearAnimation();
timeItem.setTag(null);
if (animated) {
timeItem.animate().setDuration(180).alpha(0.0f).scaleX(0.0f).scaleY(0.0f).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
timeItem.setVisibility(GONE);
super.onAnimationEnd(animation);
}
}).start();
} else {
timeItem.setVisibility(GONE);
timeItem.setAlpha(0.0f);
timeItem.setScaleY(0.0f);
timeItem.setScaleX(0.0f);
}
}
public void setTime(int value, boolean animated) {
if (timerDrawable == null) {
return;
}
boolean show = true;
if (value == 0 && !secretChatTimer) {
show = false;
return;
}
if (show) {
showTimeItem(animated);
timerDrawable.setTime(value);
} else {
hideTimeItem(animated);
}
}
private boolean rightDrawableIsScamOrVerified = false;
private String rightDrawableContentDescription = null;
private String rightDrawable2ContentDescription = null;
public void setTitleIcons(Drawable leftIcon, Drawable mutedIcon) {
titleTextView.setLeftDrawable(leftIcon);
if (!rightDrawableIsScamOrVerified) {
if (mutedIcon != null) {
rightDrawable2ContentDescription = LocaleController.getString("NotificationsMuted", R.string.NotificationsMuted);
} else {
rightDrawable2ContentDescription = null;
}
titleTextView.setRightDrawable2(mutedIcon);
}
}
public void setTitle(CharSequence value) {
setTitle(value, false, false, false, false, null, false);
}
public void setTitle(CharSequence value, boolean scam, boolean fake, boolean verified, boolean premium, TLRPC.EmojiStatus emojiStatus, boolean animated) {
if (value != null) {
value = Emoji.replaceEmoji(value, titleTextView.getPaint().getFontMetricsInt(), AndroidUtilities.dp(24), false);
}
titleTextView.setText(value);
if (scam || fake) {
if (!(titleTextView.getRightDrawable() instanceof ScamDrawable)) {
ScamDrawable drawable = new ScamDrawable(11, scam ? 0 : 1);
drawable.setColor(getThemedColor(Theme.key_actionBarDefaultSubtitle));
titleTextView.setRightDrawable2(drawable);
// titleTextView.setRightPadding(0);
rightDrawable2ContentDescription = LocaleController.getString("ScamMessage", R.string.ScamMessage);
rightDrawableIsScamOrVerified = true;
}
} else if (verified) {
Drawable verifiedBackground = getResources().getDrawable(R.drawable.verified_area).mutate();
verifiedBackground.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_profile_verifiedBackground), PorterDuff.Mode.MULTIPLY));
Drawable verifiedCheck = getResources().getDrawable(R.drawable.verified_check).mutate();
verifiedCheck.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_profile_verifiedCheck), PorterDuff.Mode.MULTIPLY));
Drawable verifiedDrawable = new CombinedDrawable(verifiedBackground, verifiedCheck);
titleTextView.setRightDrawable2(verifiedDrawable);
rightDrawableIsScamOrVerified = true;
rightDrawable2ContentDescription = LocaleController.getString("AccDescrVerified", R.string.AccDescrVerified);
} else if (titleTextView.getRightDrawable() instanceof ScamDrawable) {
titleTextView.setRightDrawable2(null);
rightDrawableIsScamOrVerified = false;
rightDrawable2ContentDescription = null;
}
if (premium || DialogObject.getEmojiStatusDocumentId(emojiStatus) != 0) {
if (titleTextView.getRightDrawable() instanceof AnimatedEmojiDrawable.WrapSizeDrawable &&
((AnimatedEmojiDrawable.WrapSizeDrawable) titleTextView.getRightDrawable()).getDrawable() instanceof AnimatedEmojiDrawable) {
((AnimatedEmojiDrawable) ((AnimatedEmojiDrawable.WrapSizeDrawable) titleTextView.getRightDrawable()).getDrawable()).removeView(titleTextView);
}
if (DialogObject.getEmojiStatusDocumentId(emojiStatus) != 0) {
emojiStatusDrawable.set(DialogObject.getEmojiStatusDocumentId(emojiStatus), animated);
} else if (premium) {
Drawable drawable = ContextCompat.getDrawable(ApplicationLoader.applicationContext, R.drawable.msg_premium_liststar).mutate();
drawable.setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_profile_verifiedBackground), PorterDuff.Mode.MULTIPLY));
emojiStatusDrawable.set(drawable, animated);
} else {
emojiStatusDrawable.set((Drawable) null, animated);
}
emojiStatusDrawable.setColor(getThemedColor(Theme.key_profile_verifiedBackground));
titleTextView.setRightDrawable(emojiStatusDrawable);
rightDrawableIsScamOrVerified = false;
rightDrawableContentDescription = LocaleController.getString("AccDescrPremium", R.string.AccDescrPremium);
} else {
titleTextView.setRightDrawable(null);
rightDrawableContentDescription = null;
}
}
public void setSubtitle(CharSequence value) {
if (lastSubtitle == null) {
if (subtitleTextView != null) {
subtitleTextView.setText(value);
} else if (animatedSubtitleTextView != null) {
animatedSubtitleTextView.setText(value);
}
} else {
lastSubtitle = value;
}
}
public ImageView getTimeItem() {
return timeItem;
}
public SimpleTextView getTitleTextView() {
return titleTextView;
}
public View getSubtitleTextView() {
if (subtitleTextView != null) {
return subtitleTextView;
}
if (animatedSubtitleTextView != null) {
return animatedSubtitleTextView;
}
return null;
}
public TextPaint getSubtitlePaint() {
return subtitleTextView != null ? subtitleTextView.getTextPaint() : animatedSubtitleTextView.getPaint();
}
public void onDestroy() {
if (sharedMediaPreloader != null) {
sharedMediaPreloader.onDestroy(parentFragment);
}
}
private void setTypingAnimation(boolean start) {
if (subtitleTextView == null) return;
if (start) {
try {
int type = MessagesController.getInstance(currentAccount).getPrintingStringType(parentFragment.getDialogId(), parentFragment.getThreadId());
if (type == 5) {
subtitleTextView.replaceTextWithDrawable(statusDrawables[type], "**oo**");
statusDrawables[type].setColor(getThemedColor(Theme.key_chat_status));
subtitleTextView.setLeftDrawable(null);
} else {
subtitleTextView.replaceTextWithDrawable(null, null);
statusDrawables[type].setColor(getThemedColor(Theme.key_chat_status));
subtitleTextView.setLeftDrawable(statusDrawables[type]);
}
currentTypingDrawable = statusDrawables[type];
for (int a = 0; a < statusDrawables.length; a++) {
if (a == type) {
statusDrawables[a].start();
} else {
statusDrawables[a].stop();
}
}
} catch (Exception e) {
FileLog.e(e);
}
} else {
currentTypingDrawable = null;
subtitleTextView.setLeftDrawable(null);
subtitleTextView.replaceTextWithDrawable(null, null);
for (int a = 0; a < statusDrawables.length; a++) {
statusDrawables[a].stop();
}
}
}
public void updateSubtitle() {
updateSubtitle(false);
}
public void updateSubtitle(boolean animated) {
if (parentFragment == null) {
return;
}
if (parentFragment.getChatMode() == ChatActivity.MODE_EDIT_BUSINESS_LINK) {
setSubtitle(BusinessLinksController.stripHttps(parentFragment.businessLink.link));
return;
}
TLRPC.User user = parentFragment.getCurrentUser();
if ((UserObject.isUserSelf(user) || UserObject.isReplyUser(user) || parentFragment.getChatMode() != 0) && parentFragment.getChatMode() != ChatActivity.MODE_SAVED) {
if (getSubtitleTextView().getVisibility() != GONE) {
getSubtitleTextView().setVisibility(GONE);
}
return;
}
TLRPC.Chat chat = parentFragment.getCurrentChat();
CharSequence printString = MessagesController.getInstance(currentAccount).getPrintingString(parentFragment.getDialogId(), parentFragment.getThreadId(), false);
if (printString != null) {
printString = TextUtils.replace(printString, new String[]{"..."}, new String[]{""});
}
CharSequence newSubtitle;
boolean useOnlineColor = false;
if (printString == null || printString.length() == 0 || ChatObject.isChannel(chat) && !chat.megagroup) {
if (parentFragment.isThreadChat() && !parentFragment.isTopic) {
if (titleTextView.getTag() != null) {
return;
}
titleTextView.setTag(1);
if (titleAnimation != null) {
titleAnimation.cancel();
titleAnimation = null;
}
if (animated) {
titleAnimation = new AnimatorSet();
titleAnimation.playTogether(
ObjectAnimator.ofFloat(titleTextView, View.TRANSLATION_Y, AndroidUtilities.dp(9.7f)),
ObjectAnimator.ofFloat(getSubtitleTextView(), View.ALPHA, 0.0f));
titleAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationCancel(Animator animation) {
titleAnimation = null;
}
@Override
public void onAnimationEnd(Animator animation) {
if (titleAnimation == animation) {
getSubtitleTextView().setVisibility(INVISIBLE);
titleAnimation = null;
}
}
});
titleAnimation.setDuration(180);
titleAnimation.start();
} else {
titleTextView.setTranslationY(AndroidUtilities.dp(9.7f));
getSubtitleTextView().setAlpha(0.0f);
getSubtitleTextView().setVisibility(INVISIBLE);
}
return;
}
setTypingAnimation(false);
if (parentFragment.getChatMode() == ChatActivity.MODE_SAVED) {
int messagesCount = parentFragment.getMessagesController().getSavedMessagesController().getMessagesCount(parentFragment.getSavedDialogId());
newSubtitle = LocaleController.formatPluralString("SavedMessagesCount", Math.max(1, messagesCount));
} else if (parentFragment.isTopic && chat != null) {
TLRPC.TL_forumTopic topic = MessagesController.getInstance(currentAccount).getTopicsController().findTopic(chat.id, parentFragment.getTopicId());
int count = 0;
if (topic != null) {
count = topic.totalMessagesCount - 1;
}
if (count > 0) {
newSubtitle = LocaleController.formatPluralString("messages", count, count);
} else {
newSubtitle = LocaleController.formatString("TopicProfileStatus", R.string.TopicProfileStatus, chat.title);
}
} else if (chat != null) {
TLRPC.ChatFull info = parentFragment.getCurrentChatInfo();
newSubtitle = getChatSubtitle(chat, info, onlineCount);
} else if (user != null) {
TLRPC.User newUser = MessagesController.getInstance(currentAccount).getUser(user.id);
if (newUser != null) {
user = newUser;
}
String newStatus;
if (UserObject.isReplyUser(user)) {
newStatus = "";
} else if (user.id == UserConfig.getInstance(currentAccount).getClientUserId()) {
newStatus = LocaleController.getString("ChatYourSelf", R.string.ChatYourSelf);
} else if (user.id == 333000 || user.id == 777000 || user.id == 42777) {
newStatus = LocaleController.getString("ServiceNotifications", R.string.ServiceNotifications);
} else if (MessagesController.isSupportUser(user)) {
newStatus = LocaleController.getString("SupportStatus", R.string.SupportStatus);
} else if (user.bot) {
newStatus = LocaleController.getString("Bot", R.string.Bot);
} else {
isOnline[0] = false;
newStatus = LocaleController.formatUserStatus(currentAccount, user, isOnline, allowShorterStatus ? statusMadeShorter : null);
useOnlineColor = isOnline[0];
}
newSubtitle = newStatus;
} else {
newSubtitle = "";
}
} else {
if (parentFragment.isThreadChat()) {
if (titleTextView.getTag() != null) {
titleTextView.setTag(null);
getSubtitleTextView().setVisibility(VISIBLE);
if (titleAnimation != null) {
titleAnimation.cancel();
titleAnimation = null;
}
if (animated) {
titleAnimation = new AnimatorSet();
titleAnimation.playTogether(
ObjectAnimator.ofFloat(titleTextView, View.TRANSLATION_Y, 0),
ObjectAnimator.ofFloat(getSubtitleTextView(), View.ALPHA, 1.0f));
titleAnimation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
titleAnimation = null;
}
});
titleAnimation.setDuration(180);
titleAnimation.start();
} else {
titleTextView.setTranslationY(0.0f);
getSubtitleTextView().setAlpha(1.0f);
}
}
}
newSubtitle = printString;
if (MessagesController.getInstance(currentAccount).getPrintingStringType(parentFragment.getDialogId(), parentFragment.getThreadId()) == 5) {
newSubtitle = Emoji.replaceEmoji(newSubtitle, getSubtitlePaint().getFontMetricsInt(), AndroidUtilities.dp(15), false);
}
useOnlineColor = true;
setTypingAnimation(true);
}
lastSubtitleColorKey = useOnlineColor ? Theme.key_chat_status : Theme.key_actionBarDefaultSubtitle;
if (lastSubtitle == null) {
if (subtitleTextView != null) {
subtitleTextView.setText(newSubtitle);
if (overrideSubtitleColor == null) {
subtitleTextView.setTextColor(getThemedColor(lastSubtitleColorKey));
subtitleTextView.setTag(lastSubtitleColorKey);
} else {
subtitleTextView.setTextColor(overrideSubtitleColor);
}
} else {
animatedSubtitleTextView.setText(newSubtitle, animated);
if (overrideSubtitleColor == null) {
animatedSubtitleTextView.setTextColor(getThemedColor(lastSubtitleColorKey));
animatedSubtitleTextView.setTag(lastSubtitleColorKey);
} else {
animatedSubtitleTextView.setTextColor(overrideSubtitleColor);
}
}
} else {
lastSubtitle = newSubtitle;
}
}
public static CharSequence getChatSubtitle(TLRPC.Chat chat, TLRPC.ChatFull info, int onlineCount) {
CharSequence newSubtitle = null;
if (ChatObject.isChannel(chat)) {
if (info != null && info.participants_count != 0) {
if (chat.megagroup) {
if (onlineCount > 1) {
newSubtitle = String.format("%s, %s", LocaleController.formatPluralString("Members", info.participants_count), LocaleController.formatPluralString("OnlineCount", Math.min(onlineCount, info.participants_count)));
} else {
newSubtitle = LocaleController.formatPluralString("Members", info.participants_count);
}
} else {
int[] result = new int[1];
boolean ignoreShort = AndroidUtilities.isAccessibilityScreenReaderEnabled();
String shortNumber = ignoreShort ? String.valueOf(result[0] = info.participants_count) : LocaleController.formatShortNumber(info.participants_count, result);
if (chat.megagroup) {
newSubtitle = LocaleController.formatPluralString("Members", result[0]).replace(String.format("%d", result[0]), shortNumber);
} else {
newSubtitle = LocaleController.formatPluralString("Subscribers", result[0]).replace(String.format("%d", result[0]), shortNumber);
}
}
} else {
if (chat.megagroup) {
if (info == null) {
newSubtitle = LocaleController.getString("Loading", R.string.Loading).toLowerCase();
} else {
if (chat.has_geo) {
newSubtitle = LocaleController.getString("MegaLocation", R.string.MegaLocation).toLowerCase();
} else if (ChatObject.isPublic(chat)) {
newSubtitle = LocaleController.getString("MegaPublic", R.string.MegaPublic).toLowerCase();
} else {
newSubtitle = LocaleController.getString("MegaPrivate", R.string.MegaPrivate).toLowerCase();
}
}
} else {
if (ChatObject.isPublic(chat)) {
newSubtitle = LocaleController.getString("ChannelPublic", R.string.ChannelPublic).toLowerCase();
} else {
newSubtitle = LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate).toLowerCase();
}
}
}
} else {
if (ChatObject.isKickedFromChat(chat)) {
newSubtitle = LocaleController.getString("YouWereKicked", R.string.YouWereKicked);
} else if (ChatObject.isLeftFromChat(chat)) {
newSubtitle = LocaleController.getString("YouLeft", R.string.YouLeft);
} else {
int count = chat.participants_count;
if (info != null && info.participants != null) {
count = info.participants.participants.size();
}
if (onlineCount > 1 && count != 0) {
newSubtitle = String.format("%s, %s", LocaleController.formatPluralString("Members", count), LocaleController.formatPluralString("OnlineCount", onlineCount));
} else {
newSubtitle = LocaleController.formatPluralString("Members", count);
}
}
}
return newSubtitle;
}
public int getLastSubtitleColorKey() {
return lastSubtitleColorKey;
}
public void setChatAvatar(TLRPC.Chat chat) {
avatarDrawable.setInfo(currentAccount, chat);
if (avatarImageView != null) {
avatarImageView.setForUserOrChat(chat, avatarDrawable);
avatarImageView.setRoundRadius(ChatObject.isForum(chat) ? AndroidUtilities.dp(ChatObject.hasStories(chat) ? 11 : 16) : AndroidUtilities.dp(21));
}
}
public void setUserAvatar(TLRPC.User user) {
setUserAvatar(user, false);
}
public void setUserAvatar(TLRPC.User user, boolean showSelf) {
avatarDrawable.setInfo(currentAccount, user);
if (UserObject.isReplyUser(user)) {
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_REPLIES);
avatarDrawable.setScaleSize(.8f);
if (avatarImageView != null) {
avatarImageView.setImage(null, null, avatarDrawable, user);
}
} else if (UserObject.isAnonymous(user)) {
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_ANONYMOUS);
avatarDrawable.setScaleSize(.8f);
if (avatarImageView != null) {
avatarImageView.setImage(null, null, avatarDrawable, user);
}
} else if (UserObject.isUserSelf(user) && !showSelf) {
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_SAVED);
avatarDrawable.setScaleSize(.8f);
if (avatarImageView != null) {
avatarImageView.setImage(null, null, avatarDrawable, user);
}
} else {
avatarDrawable.setScaleSize(1f);
if (avatarImageView != null) {
avatarImageView.setForUserOrChat(user, avatarDrawable);
}
}
}
public void checkAndUpdateAvatar() {
if (parentFragment == null) {
return;
}
TLRPC.User user = parentFragment.getCurrentUser();
TLRPC.Chat chat = parentFragment.getCurrentChat();
if (parentFragment.getChatMode() == ChatActivity.MODE_SAVED) {
long dialogId = parentFragment.getSavedDialogId();
if (dialogId >= 0) {
user = parentFragment.getMessagesController().getUser(dialogId);
chat = null;
} else {
user = null;
chat = parentFragment.getMessagesController().getChat(-dialogId);
}
}
if (user != null) {
avatarDrawable.setInfo(currentAccount, user);
if (UserObject.isReplyUser(user)) {
avatarDrawable.setScaleSize(.8f);
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_REPLIES);
if (avatarImageView != null) {
avatarImageView.setImage(null, null, avatarDrawable, user);
}
} else if (UserObject.isAnonymous(user)) {
avatarDrawable.setScaleSize(.8f);
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_ANONYMOUS);
if (avatarImageView != null) {
avatarImageView.setImage(null, null, avatarDrawable, user);
}
} else if (UserObject.isUserSelf(user) && parentFragment.getChatMode() == ChatActivity.MODE_SAVED) {
avatarDrawable.setScaleSize(.8f);
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_MY_NOTES);
if (avatarImageView != null) {
avatarImageView.setImage(null, null, avatarDrawable, user);
}
} else if (UserObject.isUserSelf(user)) {
avatarDrawable.setScaleSize(.8f);
avatarDrawable.setAvatarType(AvatarDrawable.AVATAR_TYPE_SAVED);
if (avatarImageView != null) {
avatarImageView.setImage(null, null, avatarDrawable, user);
}
} else {
avatarDrawable.setScaleSize(1f);
if (avatarImageView != null) {
avatarImageView.imageReceiver.setForUserOrChat(user, avatarDrawable, null, true, VectorAvatarThumbDrawable.TYPE_STATIC, false);
}
}
} else if (chat != null) {
avatarDrawable.setInfo(currentAccount, chat);
if (avatarImageView != null) {
avatarImageView.setForUserOrChat(chat, avatarDrawable);
}
avatarImageView.setRoundRadius(chat.forum ? AndroidUtilities.dp(ChatObject.hasStories(chat) ? 11 : 16) : AndroidUtilities.dp(21));
}
}
public void updateOnlineCount() {
if (parentFragment == null) {
return;
}
onlineCount = 0;
TLRPC.ChatFull info = parentFragment.getCurrentChatInfo();
if (info == null) {
return;
}
int currentTime = ConnectionsManager.getInstance(currentAccount).getCurrentTime();
if (info instanceof TLRPC.TL_chatFull || info instanceof TLRPC.TL_channelFull && info.participants_count <= 200 && info.participants != null) {
for (int a = 0; a < info.participants.participants.size(); a++) {
TLRPC.ChatParticipant participant = info.participants.participants.get(a);
TLRPC.User user = MessagesController.getInstance(currentAccount).getUser(participant.user_id);
if (user != null && user.status != null && (user.status.expires > currentTime || user.id == UserConfig.getInstance(currentAccount).getClientUserId()) && user.status.expires > 10000) {
onlineCount++;
}
}
} else if (info instanceof TLRPC.TL_channelFull && info.participants_count > 200) {
onlineCount = info.online_count;
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (parentFragment != null) {
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.didUpdateConnectionState);
NotificationCenter.getGlobalInstance().addObserver(this, NotificationCenter.emojiLoaded);
if (parentFragment.getChatMode() == ChatActivity.MODE_SAVED) {
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.savedMessagesDialogsUpdate);
}
currentConnectionState = ConnectionsManager.getInstance(currentAccount).getConnectionState();
updateCurrentConnectionState();
}
if (emojiStatusDrawable != null) {
emojiStatusDrawable.attach();
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (parentFragment != null) {
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.didUpdateConnectionState);
NotificationCenter.getGlobalInstance().removeObserver(this, NotificationCenter.emojiLoaded);
if (parentFragment.getChatMode() == ChatActivity.MODE_SAVED) {
NotificationCenter.getInstance(currentAccount).removeObserver(this, NotificationCenter.savedMessagesDialogsUpdate);
}
}
if (emojiStatusDrawable != null) {
emojiStatusDrawable.detach();
}
}
@Override
public void didReceivedNotification(int id, int account, Object... args) {
if (id == NotificationCenter.didUpdateConnectionState) {
int state = ConnectionsManager.getInstance(currentAccount).getConnectionState();
if (currentConnectionState != state) {
currentConnectionState = state;
updateCurrentConnectionState();
}
} else if (id == NotificationCenter.emojiLoaded) {
if (titleTextView != null) {
titleTextView.invalidate();
}
if (getSubtitleTextView() != null) {
getSubtitleTextView().invalidate();
}
invalidate();
} else if (id == NotificationCenter.savedMessagesDialogsUpdate) {
updateSubtitle(true);
}
}
private void updateCurrentConnectionState() {
String title = null;
if (currentConnectionState == ConnectionsManager.ConnectionStateWaitingForNetwork) {
title = LocaleController.getString("WaitingForNetwork", R.string.WaitingForNetwork);
} else if (currentConnectionState == ConnectionsManager.ConnectionStateConnecting) {
title = LocaleController.getString("Connecting", R.string.Connecting);
} else if (currentConnectionState == ConnectionsManager.ConnectionStateUpdating) {
title = LocaleController.getString("Updating", R.string.Updating);
} else if (currentConnectionState == ConnectionsManager.ConnectionStateConnectingToProxy) {
title = LocaleController.getString("ConnectingToProxy", R.string.ConnectingToProxy);
}
if (title == null) {
if (lastSubtitle != null) {
if (subtitleTextView != null) {
subtitleTextView.setText(lastSubtitle);
lastSubtitle = null;
if (overrideSubtitleColor != null) {
subtitleTextView.setTextColor(overrideSubtitleColor);
} else if (lastSubtitleColorKey >= 0) {
subtitleTextView.setTextColor(getThemedColor(lastSubtitleColorKey));
subtitleTextView.setTag(lastSubtitleColorKey);
}
} else if (animatedSubtitleTextView != null) {
animatedSubtitleTextView.setText(lastSubtitle, !LocaleController.isRTL);
lastSubtitle = null;
if (overrideSubtitleColor != null) {
animatedSubtitleTextView.setTextColor(overrideSubtitleColor);
} else if (lastSubtitleColorKey >= 0) {
animatedSubtitleTextView.setTextColor(getThemedColor(lastSubtitleColorKey));
animatedSubtitleTextView.setTag(lastSubtitleColorKey);
}
}
}
} else {
if (subtitleTextView != null) {
if (lastSubtitle == null) {
lastSubtitle = subtitleTextView.getText();
}
subtitleTextView.setText(title);
if (overrideSubtitleColor != null) {
subtitleTextView.setTextColor(overrideSubtitleColor);
} else {
subtitleTextView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubtitle));
subtitleTextView.setTag(Theme.key_actionBarDefaultSubtitle);
}
} else if (animatedSubtitleTextView != null) {
if (lastSubtitle == null) {
lastSubtitle = animatedSubtitleTextView.getText();
}
animatedSubtitleTextView.setText(title, !LocaleController.isRTL);
if (overrideSubtitleColor != null) {
animatedSubtitleTextView.setTextColor(overrideSubtitleColor);
} else {
animatedSubtitleTextView.setTextColor(getThemedColor(Theme.key_actionBarDefaultSubtitle));
animatedSubtitleTextView.setTag(Theme.key_actionBarDefaultSubtitle);
}
}
}
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
StringBuilder sb = new StringBuilder();
sb.append(titleTextView.getText());
if (rightDrawableContentDescription != null) {
sb.append(", ");
sb.append(rightDrawableContentDescription);
}
if (rightDrawable2ContentDescription != null) {
sb.append(", ");
sb.append(rightDrawable2ContentDescription);
}
sb.append("\n");
if (subtitleTextView != null) {
sb.append(subtitleTextView.getText());
} else if (animatedSubtitleTextView != null) {
sb.append(animatedSubtitleTextView.getText());
}
info.setContentDescription(sb);
if (info.isClickable() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
info.addAction(new AccessibilityNodeInfo.AccessibilityAction(AccessibilityNodeInfo.ACTION_CLICK, LocaleController.getString("OpenProfile", R.string.OpenProfile)));
}
}
public SharedMediaLayout.SharedMediaPreloader getSharedMediaPreloader() {
return sharedMediaPreloader;
}
public BackupImageView getAvatarImageView() {
return avatarImageView;
}
private int getThemedColor(int key) {
return Theme.getColor(key, resourcesProvider);
}
public void updateColors() {
if (currentTypingDrawable != null) {
currentTypingDrawable.setColor(getThemedColor(Theme.key_chat_status));
}
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/org/telegram/ui/Components/ChatAvatarContainer.java |
45,340 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Cells;
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Typeface;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MessagesController;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.R;
import org.telegram.messenger.UserConfig;
import org.telegram.messenger.UserObject;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.SimpleTextView;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Components.AvatarDrawable;
import org.telegram.ui.Components.BackupImageView;
import org.telegram.ui.Components.CheckBox;
import org.telegram.ui.Components.CheckBoxSquare;
import org.telegram.ui.Components.LayoutHelper;
public class UserCell2 extends FrameLayout {
private Theme.ResourcesProvider resourcesProvider;
private BackupImageView avatarImageView;
private SimpleTextView nameTextView;
private SimpleTextView statusTextView;
private ImageView imageView;
private CheckBox checkBox;
private CheckBoxSquare checkBoxBig;
private AvatarDrawable avatarDrawable;
private TLObject currentObject;
private CharSequence currentName;
private CharSequence currentStatus;
private int currentId;
private int currentDrawable;
private String lastName;
private int lastStatus;
private TLRPC.FileLocation lastAvatar;
private int currentAccount = UserConfig.selectedAccount;
private int statusColor;
private int statusOnlineColor;
public UserCell2(Context context, int padding, int checkbox) {
this(context, padding, checkbox, null);
}
public UserCell2(Context context, int padding, int checkbox, Theme.ResourcesProvider resourcesProvider) {
super(context);
this.resourcesProvider = resourcesProvider;
statusColor = Theme.getColor(Theme.key_windowBackgroundWhiteGrayText, resourcesProvider);
statusOnlineColor = Theme.getColor(Theme.key_windowBackgroundWhiteBlueText, resourcesProvider);
avatarDrawable = new AvatarDrawable();
avatarImageView = new BackupImageView(context);
avatarImageView.setRoundRadius(AndroidUtilities.dp(24));
addView(avatarImageView, LayoutHelper.createFrame(48, 48, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 7 + padding, 11, LocaleController.isRTL ? 7 + padding : 0, 0));
nameTextView = new SimpleTextView(context) {
@Override
public boolean setText(CharSequence value) {
value = Emoji.replaceEmoji(value, getPaint().getFontMetricsInt(), AndroidUtilities.dp(15), false);
return super.setText(value);
}
};
NotificationCenter.listenEmojiLoading(nameTextView);
nameTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText, resourcesProvider));
nameTextView.setTextSize(17);
nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 28 + (checkbox == 2 ? 18 : 0) : (68 + padding), 14.5f, LocaleController.isRTL ? (68 + padding) : 28 + (checkbox == 2 ? 18 : 0), 0));
statusTextView = new SimpleTextView(context);
statusTextView.setTextSize(14);
statusTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP);
addView(statusTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 20, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 28 : (68 + padding), 37.5f, LocaleController.isRTL ? (68 + padding) : 28, 0));
imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayIcon, resourcesProvider), PorterDuff.Mode.MULTIPLY));
imageView.setVisibility(GONE);
addView(imageView, LayoutHelper.createFrame(LayoutParams.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 0 : 16, 0, LocaleController.isRTL ? 16 : 0, 0));
if (checkbox == 2) {
checkBoxBig = new CheckBoxSquare(context, false, resourcesProvider);
addView(checkBoxBig, LayoutHelper.createFrame(18, 18, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 19 : 0, 0, LocaleController.isRTL ? 0 : 19, 0));
} else if (checkbox == 1) {
checkBox = new CheckBox(context, R.drawable.round_check2);
checkBox.setVisibility(INVISIBLE);
checkBox.setColor(Theme.getColor(Theme.key_checkbox, resourcesProvider), Theme.getColor(Theme.key_checkboxCheck, resourcesProvider));
addView(checkBox, LayoutHelper.createFrame(22, 22, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 37 + padding, 41, LocaleController.isRTL ? 37 + padding : 0, 0));
}
}
public void setData(TLObject object, CharSequence name, CharSequence status, int resId) {
if (object == null && name == null && status == null) {
currentStatus = null;
currentName = null;
currentObject = null;
nameTextView.setText("");
statusTextView.setText("");
avatarImageView.setImageDrawable(null);
return;
}
currentStatus = status;
currentName = name;
currentObject = object;
currentDrawable = resId;
update(0);
}
public void setNameTypeface(Typeface typeface) {
nameTextView.setTypeface(typeface);
}
public void setCurrentId(int id) {
currentId = id;
}
public void setChecked(boolean checked, boolean animated) {
if (checkBox != null) {
if (checkBox.getVisibility() != VISIBLE) {
checkBox.setVisibility(VISIBLE);
}
checkBox.setChecked(checked, animated);
} else if (checkBoxBig != null) {
if (checkBoxBig.getVisibility() != VISIBLE) {
checkBoxBig.setVisibility(VISIBLE);
}
checkBoxBig.setChecked(checked, animated);
}
}
public void setCheckDisabled(boolean disabled) {
if (checkBoxBig != null) {
checkBoxBig.setDisabled(disabled);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(70), MeasureSpec.EXACTLY));
}
public void setStatusColors(int color, int onlineColor) {
statusColor = color;
statusOnlineColor = onlineColor;
}
@Override
public void invalidate() {
super.invalidate();
if (checkBoxBig != null) {
checkBoxBig.invalidate();
}
}
public void update(int mask) {
TLRPC.FileLocation photo = null;
String newName = null;
TLRPC.User currentUser = null;
TLRPC.Chat currentChat = null;
if (currentObject instanceof TLRPC.User) {
currentUser = (TLRPC.User) currentObject;
if (currentUser.photo != null) {
photo = currentUser.photo.photo_small;
}
} else if (currentObject instanceof TLRPC.Chat) {
currentChat = (TLRPC.Chat) currentObject;
if (currentChat.photo != null) {
photo = currentChat.photo.photo_small;
}
}
if (mask != 0) {
boolean continueUpdate = false;
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0) {
if (lastAvatar != null && photo == null || lastAvatar == null && photo != null || lastAvatar != null && photo != null && (lastAvatar.volume_id != photo.volume_id || lastAvatar.local_id != photo.local_id)) {
continueUpdate = true;
}
}
if (currentUser != null && !continueUpdate && (mask & MessagesController.UPDATE_MASK_STATUS) != 0) {
int newStatus = 0;
if (currentUser.status != null) {
newStatus = currentUser.status.expires;
}
if (newStatus != lastStatus) {
continueUpdate = true;
}
}
if (!continueUpdate && currentName == null && lastName != null && (mask & MessagesController.UPDATE_MASK_NAME) != 0) {
if (currentUser != null) {
newName = UserObject.getUserName(currentUser);
} else {
newName = currentChat.title;
}
if (!newName.equals(lastName)) {
continueUpdate = true;
}
}
if (!continueUpdate) {
return;
}
}
lastAvatar = photo;
if (currentUser != null) {
avatarDrawable.setInfo(currentAccount, currentUser);
if (currentUser.status != null) {
lastStatus = currentUser.status.expires;
} else {
lastStatus = 0;
}
} else if (currentChat != null) {
avatarDrawable.setInfo(currentAccount, currentChat);
} else if (currentName != null) {
avatarDrawable.setInfo(currentId, currentName.toString(), null);
} else {
avatarDrawable.setInfo(currentId, "#", null);
}
if (currentName != null) {
lastName = null;
nameTextView.setText(currentName);
} else {
if (currentUser != null) {
lastName = newName == null ? UserObject.getUserName(currentUser) : newName;
} else {
lastName = newName == null ? currentChat.title : newName;
}
nameTextView.setText(lastName);
}
if (currentStatus != null) {
statusTextView.setTextColor(statusColor);
statusTextView.setText(currentStatus);
if (avatarImageView != null) {
avatarImageView.setForUserOrChat(currentUser, avatarDrawable);
}
} else if (currentUser != null) {
if (currentUser.bot) {
statusTextView.setTextColor(statusColor);
if (currentUser.bot_chat_history) {
statusTextView.setText(LocaleController.getString("BotStatusRead", R.string.BotStatusRead));
} else {
statusTextView.setText(LocaleController.getString("BotStatusCantRead", R.string.BotStatusCantRead));
}
} else {
if (currentUser.id == UserConfig.getInstance(currentAccount).getClientUserId() || currentUser.status != null && currentUser.status.expires > ConnectionsManager.getInstance(currentAccount).getCurrentTime() || MessagesController.getInstance(currentAccount).onlinePrivacy.containsKey(currentUser.id)) {
statusTextView.setTextColor(statusOnlineColor);
statusTextView.setText(LocaleController.getString("Online", R.string.Online));
} else {
statusTextView.setTextColor(statusColor);
statusTextView.setText(LocaleController.formatUserStatus(currentAccount, currentUser));
}
}
avatarImageView.setForUserOrChat(currentUser, avatarDrawable);
} else if (currentChat != null) {
statusTextView.setTextColor(statusColor);
if (ChatObject.isChannel(currentChat) && !currentChat.megagroup) {
if (currentChat.participants_count != 0) {
statusTextView.setText(LocaleController.formatPluralString("Subscribers", currentChat.participants_count));
} else if (!ChatObject.isPublic(currentChat)) {
statusTextView.setText(LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate));
} else {
statusTextView.setText(LocaleController.getString("ChannelPublic", R.string.ChannelPublic));
}
} else {
if (currentChat.participants_count != 0) {
statusTextView.setText(LocaleController.formatPluralString("Members", currentChat.participants_count));
} else if (currentChat.has_geo) {
statusTextView.setText(LocaleController.getString("MegaLocation", R.string.MegaLocation));
} else if (!ChatObject.isPublic(currentChat)) {
statusTextView.setText(LocaleController.getString("MegaPrivate", R.string.MegaPrivate));
} else {
statusTextView.setText(LocaleController.getString("MegaPublic", R.string.MegaPublic));
}
}
avatarImageView.setForUserOrChat(currentChat, avatarDrawable);
} else {
avatarImageView.setImageDrawable(avatarDrawable);
}
avatarImageView.setRoundRadius(currentChat != null && currentChat.forum ? AndroidUtilities.dp(14) : AndroidUtilities.dp(24));
if (imageView.getVisibility() == VISIBLE && currentDrawable == 0 || imageView.getVisibility() == GONE && currentDrawable != 0) {
imageView.setVisibility(currentDrawable == 0 ? GONE : VISIBLE);
imageView.setImageResource(currentDrawable);
}
}
@Override
public boolean hasOverlappingRendering() {
return false;
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/org/telegram/ui/Cells/UserCell2.java |
45,341 | /*
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2012/01/12 Reflected the rename of the class ExtensionPopupMenu to
// ExtensionPopupMenuItem.
// ZAP: 2012/03/15 Added the method addPopupMenuItem(ExtensionPopupMenu menu).
// ZAP: 2012/05/03 Changed to only initialise the class variables MENU_SEPARATOR
// and POPUP_MENU_SEPARATOR if there is a view.
// ZAP: 2014/01/28 Issue 207: Support keyboard shortcuts
// ZAP: 2014/05/02 Fixed method links in Javadocs
// ZAP: 2014/11/11 Issue 1406: Move online menu items to an add-on
// ZAP: 2016/09/26 JavaDoc tweaks
// ZAP: 2018/10/05 Lazily initialise the lists and add JavaDoc.
// ZAP: 2019/03/15 Issue 3578: Added the method addImportMenuItem(ZapMenuItem menuitem)
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
package org.parosproxy.paros.extension;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import org.parosproxy.paros.view.View;
import org.zaproxy.zap.extension.ExtensionPopupMenu;
import org.zaproxy.zap.view.ZapMenuItem;
/**
* The object to add/hook menus and menu items to the {@link
* org.parosproxy.paros.view.MainFrame#getMainMenuBar() main menu bar} and to the {@link
* View#getPopupMenu() main context menu}.
*
* <p>The menus added through the hook are removed when the extension is unloaded.
*
* <p><strong>Note:</strong> This class is not thread-safe, the menus should be added only through
* the thread that {@link Extension#hook(ExtensionHook) hooks the extension}.
*
* @since 1.0.0
* @see View#getMainFrame()
*/
public class ExtensionHookMenu {
public static final JMenuItem MENU_SEPARATOR;
public static final ExtensionPopupMenuItem POPUP_MENU_SEPARATOR;
/**
* The new menus for the main menu bar added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addNewMenu(JMenu)
* @see #getNewMenus()
*/
private List<JMenuItem> newMenuList;
/**
* The file menus added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addFileMenuItemImpl(JMenuItem)
* @see #getFile()
*/
private List<JMenuItem> fileMenuItemList;
/**
* The edit menus added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addEditMenuItemImpl(JMenuItem)
* @see #getEdit()
*/
private List<JMenuItem> editMenuItemList;
/**
* The view menus added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addViewMenuItemImpl(JMenuItem)
* @see #getView()
*/
private List<JMenuItem> viewMenuItemList;
/**
* The analyse menus added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addAnalyseMenuItemImpl(JMenuItem)
* @see #getAnalyse()
*/
private List<JMenuItem> analyseMenuItemList;
/**
* The tools menus added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addToolsMenuItemImpl(JMenuItem)
* @see #getTools()
*/
private List<JMenuItem> toolsMenuItemList;
/**
* The import menus added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addImportMenuItem(ZapMenuItem)
* @see #getImport()
* @since 2.8.0
*/
private List<JMenuItem> importMenuItemList;
/**
* The menus for the main context menu added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addPopupMenuImpl(JMenuItem)
* @see #getPopupMenus()
*/
private List<JMenuItem> popupMenuList;
/**
* The help menus added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addHelpMenuItemImpl(JMenuItem)
* @see #getHelpMenus()
*/
private List<JMenuItem> helpMenuList;
/**
* The report menus added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addReportMenuItemImpl(JMenuItem)
* @see #getReportMenus()
*/
private List<JMenuItem> reportMenuList;
/**
* The online menus added to this extension hook.
*
* <p>Lazily initialised.
*
* @see #addOnlineMenuItem(ZapMenuItem)
* @see #getOnlineMenus()
*/
private List<JMenuItem> onlineMenuList;
// ZAP: Added static block.
static {
// XXX temporary "hack" to check if ZAP is in GUI mode.
// There is no need to create view elements (subsequently initialising
// the java.awt.Toolkit) when ZAP is running in non GUI mode.
if (View.isInitialised()) {
MENU_SEPARATOR = new JMenuItem();
POPUP_MENU_SEPARATOR = new ExtensionPopupMenuItem();
} else {
MENU_SEPARATOR = null;
POPUP_MENU_SEPARATOR = null;
}
}
List<JMenuItem> getNewMenus() {
return unmodifiableList(newMenuList);
}
List<JMenuItem> getFile() {
return unmodifiableList(fileMenuItemList);
}
List<JMenuItem> getEdit() {
return unmodifiableList(editMenuItemList);
}
List<JMenuItem> getView() {
return unmodifiableList(viewMenuItemList);
}
List<JMenuItem> getAnalyse() {
return unmodifiableList(analyseMenuItemList);
}
List<JMenuItem> getTools() {
return unmodifiableList(toolsMenuItemList);
}
List<JMenuItem> getImport() {
return unmodifiableList(importMenuItemList);
}
/**
* Gets the popup menu items used for the whole workbench.
*
* @return a {@code List} containing the popup menu items of the extension
*/
List<JMenuItem> getPopupMenus() {
return unmodifiableList(popupMenuList);
}
List<JMenuItem> getHelpMenus() {
return unmodifiableList(helpMenuList);
}
List<JMenuItem> getReportMenus() {
return unmodifiableList(reportMenuList);
}
List<JMenuItem> getOnlineMenus() {
return unmodifiableList(onlineMenuList);
}
/**
* Add a menu item to the File menu
*
* @param menuItem the file menu item
* @deprecated use {@link #addFileMenuItem(ZapMenuItem menuItem)} instead.
*/
@Deprecated
public void addFileMenuItem(JMenuItem menuItem) {
addFileMenuItemImpl(menuItem);
}
/**
* Add a sub-menu to the File menu
*
* @param menu the sub-menu to add
* @since 2.9.0
*/
public void addFileSubMenu(JMenu menu) {
addFileMenuItemImpl(menu);
}
private void addFileMenuItemImpl(JMenuItem menuItem) {
if (fileMenuItemList == null) {
fileMenuItemList = createList();
}
fileMenuItemList.add(menuItem);
}
/**
* Add a menu item to the Edit menu
*
* @param menuItem the edit menu item
* @deprecated use {@link #addEditMenuItem(ZapMenuItem menuItem)} instead.
*/
@Deprecated
public void addEditMenuItem(JMenuItem menuItem) {
addEditMenuItemImpl(menuItem);
}
/**
* Add a sub-menu to the Edit menu
*
* @param menu the sub-menu to add
* @since 2.9.0
*/
public void addEditSubMenu(JMenu menu) {
addEditMenuItemImpl(menu);
}
private void addEditMenuItemImpl(JMenuItem menuItem) {
if (editMenuItemList == null) {
editMenuItemList = createList();
}
editMenuItemList.add(menuItem);
}
/**
* Add a menu item to the View menu
*
* @param menuItem the view menu item
* @deprecated use {@link #addViewMenuItem(ZapMenuItem menuItem)} instead.
*/
@Deprecated
public void addViewMenuItem(JMenuItem menuItem) {
addViewMenuItemImpl(menuItem);
}
/**
* Add a sub-menu to the View menu
*
* @param menu the sub-menu to add
* @since 2.9.0
*/
public void addViewSubMenu(JMenu menu) {
addViewMenuItemImpl(menu);
}
private void addViewMenuItemImpl(JMenuItem menuItem) {
if (viewMenuItemList == null) {
viewMenuItemList = createList();
}
viewMenuItemList.add(menuItem);
}
/**
* Add a menu item to the Analyse menu
*
* @param menuItem the analyse menu item
* @deprecated use {@link #addAnalyseMenuItem(ZapMenuItem menuItem)} instead.
*/
@Deprecated
public void addAnalyseMenuItem(JMenuItem menuItem) {
addAnalyseMenuItemImpl(menuItem);
}
/**
* Add a sub-menu to the Analyse menu
*
* @param menu the sub-menu to add
* @since 2.9.0
*/
public void addAnalyseSubMenu(JMenu menu) {
addAnalyseMenuItemImpl(menu);
}
private void addAnalyseMenuItemImpl(JMenuItem menuItem) {
if (analyseMenuItemList == null) {
analyseMenuItemList = createList();
}
analyseMenuItemList.add(menuItem);
}
/**
* Add a menu item to the Tools menu
*
* @param menuItem the tools menu item
* @deprecated use {@link #addToolsMenuItem(ZapMenuItem menuItem)} instead.
*/
@Deprecated
public void addToolsMenuItem(JMenuItem menuItem) {
addToolsMenuItemImpl(menuItem);
}
/**
* Add a sub-menu to the Tools menu
*
* @param menu the sub-menu to add
* @since 2.9.0
*/
public void addToolsSubMenu(JMenu menu) {
addToolsMenuItemImpl(menu);
}
private void addToolsMenuItemImpl(JMenuItem menuItem) {
if (toolsMenuItemList == null) {
toolsMenuItemList = createList();
}
toolsMenuItemList.add(menuItem);
}
public void addFileMenuItem(ZapMenuItem menuItem) {
addFileMenuItemImpl(menuItem);
}
public void addEditMenuItem(ZapMenuItem menuItem) {
addEditMenuItemImpl(menuItem);
}
public void addViewMenuItem(ZapMenuItem menuItem) {
addViewMenuItemImpl(menuItem);
}
public void addAnalyseMenuItem(ZapMenuItem menuItem) {
addAnalyseMenuItemImpl(menuItem);
}
public void addToolsMenuItem(ZapMenuItem menuItem) {
addToolsMenuItemImpl(menuItem);
}
/**
* Add a sub-menu to the Import menu
*
* @param menu the sub-menu to add
* @since 2.9.0
*/
public void addImportSubMenu(JMenu menu) {
addImportMenuItemImpl(menu);
}
/**
* @since 2.8.0
*/
public void addImportMenuItem(ZapMenuItem menuItem) {
addImportMenuItemImpl(menuItem);
}
private void addImportMenuItemImpl(JMenuItem menuItem) {
if (importMenuItemList == null) {
importMenuItemList = createList();
}
importMenuItemList.add(menuItem);
}
public void addNewMenu(JMenu menu) {
if (newMenuList == null) {
newMenuList = createList();
}
newMenuList.add(menu);
}
/**
* Add a popup menu item used for the whole workbench. Conditions can be set in PluginMenu when
* the popup menu can be used.
*
* @param menuItem the popup menu item
*/
public void addPopupMenuItem(ExtensionPopupMenuItem menuItem) {
addPopupMenuImpl(menuItem);
}
private void addPopupMenuImpl(JMenuItem menu) {
if (popupMenuList == null) {
popupMenuList = createList();
}
popupMenuList.add(menu);
}
// ZAP: Added the method.
public void addPopupMenuItem(ExtensionPopupMenu menu) {
addPopupMenuImpl(menu);
}
/**
* Add a menu item to the Help menu
*
* @param menuItem the help menu item
* @deprecated use {@link #addHelpMenuItem(ZapMenuItem menuItem)} instead.
*/
@Deprecated
public void addHelpMenuItem(JMenuItem menuItem) {
addHelpMenuItemImpl(menuItem);
}
/**
* Add a sub-menu to the Help menu
*
* @param menu the sub-menu to add
* @since 2.9.0
*/
public void addHelpSubMenu(JMenu menu) {
addHelpMenuItemImpl(menu);
}
private void addHelpMenuItemImpl(JMenuItem menuItem) {
if (helpMenuList == null) {
helpMenuList = createList();
}
helpMenuList.add(menuItem);
}
/**
* Add a menu item to the Report menu
*
* @param menuItem the report menu item
* @deprecated use {@link #addReportMenuItem(ZapMenuItem menuItem)} instead.
*/
@Deprecated
public void addReportMenuItem(JMenuItem menuItem) {
addReportMenuItemImpl(menuItem);
}
/**
* Add a sub-menu to the Report menu
*
* @param menu the sub-menu to add
* @since 2.9.0
*/
public void addReportSubMenu(JMenu menu) {
addReportMenuItemImpl(menu);
}
private void addReportMenuItemImpl(JMenuItem menuItem) {
if (reportMenuList == null) {
reportMenuList = createList();
}
reportMenuList.add(menuItem);
}
public void addHelpMenuItem(ZapMenuItem menuItem) {
addHelpMenuItemImpl(menuItem);
}
public void addReportMenuItem(ZapMenuItem menuItem) {
addReportMenuItemImpl(menuItem);
}
/**
* Add a sub-menu to the Online menu
*
* @param menu the sub-menu to add
* @since 2.9.0
*/
public void addOnlineSubMenu(JMenu menu) {
addOnlineMenuItemImpl(menu);
}
public void addOnlineMenuItem(ZapMenuItem menuItem) {
addOnlineMenuItemImpl(menuItem);
}
private void addOnlineMenuItemImpl(JMenuItem menuItem) {
if (onlineMenuList == null) {
onlineMenuList = createList();
}
onlineMenuList.add(menuItem);
}
public JMenuItem getMenuSeparator() {
return MENU_SEPARATOR;
}
public ExtensionPopupMenuItem getPopupMenuSeparator() {
return POPUP_MENU_SEPARATOR;
}
/**
* Creates an {@link ArrayList} with initial capacity of 1.
*
* <p>Most of the extensions just add one menu.
*
* @return the {@code ArrayList}.
*/
private static <T> List<T> createList() {
return new ArrayList<>(1);
}
/**
* Gets an unmodifiable list from the given list.
*
* @param list the list, might be {@code null}.
* @return an unmodifiable list, never {@code null}.
*/
private static <T> List<T> unmodifiableList(List<T> list) {
if (list == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(list);
}
}
| zaproxy/zaproxy | zap/src/main/java/org/parosproxy/paros/extension/ExtensionHookMenu.java |
45,342 | /*
* The MIT License
*
* Copyright 2015 Red Hat, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.cli;
import hudson.AbortException;
import hudson.Extension;
import hudson.model.Computer;
import java.util.HashSet;
import java.util.List;
import org.kohsuke.args4j.Argument;
/**
* CLI Command, which moves the node to the online state.
* @author pjanouse
* @since 1.642
*/
@Extension
public class OnlineNodeCommand extends CLICommand {
@Argument(metaVar = "NAME", usage = "Agent name, or empty string for built-in node", required = true, multiValued = true)
private List<String> nodes;
@Override
public String getShortDescription() {
return Messages.OnlineNodeCommand_ShortDescription();
}
@Override
protected int run() throws Exception {
boolean errorOccurred = false;
final HashSet<String> hs = new HashSet<>(nodes);
for (String node_s : hs) {
try {
Computer computer = Computer.resolveForCLI(node_s);
computer.cliOnline();
} catch (Exception e) {
if (hs.size() == 1) {
throw e;
}
final String errorMsg = node_s + ": " + e.getMessage();
stderr.println(errorMsg);
errorOccurred = true;
continue;
}
}
if (errorOccurred) {
throw new AbortException(CLI_LISTPARAM_SUMMARY_ERROR_TEXT);
}
return 0;
}
}
| NotMyFault/jenkins-gh-actions | core/src/main/java/hudson/cli/OnlineNodeCommand.java |
45,343 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DirectoryId {
/**
* A Uuid that is used to represent an unspecified log directory,
* that is expected to have been previously selected to host an
* associated replica. This contrasts with {@code UNASSIGNED_DIR},
* which is associated with (typically new) replicas that may not
* yet have been placed in any log directory.
*/
public static final Uuid MIGRATING = new Uuid(0L, 0L);
/**
* A Uuid that is used to represent directories that are pending an assignment.
*/
public static final Uuid UNASSIGNED = new Uuid(0L, 1L);
/**
* A Uuid that is used to represent unspecified offline dirs.
*/
public static final Uuid LOST = new Uuid(0L, 2L);
/**
* Static factory to generate a directory ID.
*
* This will not generate a reserved UUID (first 100), or one whose string representation
* starts with a dash ("-")
*/
public static Uuid random() {
while (true) {
// Uuid.randomUuid does not generate Uuids whose string representation starts with a
// dash.
Uuid uuid = Uuid.randomUuid();
if (!DirectoryId.reserved(uuid)) {
return uuid;
}
}
}
/**
* Check if a directory ID is part of the first 100 reserved IDs.
*
* @param uuid the directory ID to check.
* @return true only if the directory ID is reserved.
*/
public static boolean reserved(Uuid uuid) {
return uuid.getMostSignificantBits() == 0 &&
uuid.getLeastSignificantBits() < 100;
}
/**
* Calculate the new directory information based on an existing replica assignment.
* Replicas for which there already is a directory ID keep the same directory.
* All other replicas get {@link #UNASSIGNED}.
* @param currentReplicas The current replicas, represented by the broker IDs
* @param currentDirectories The current directory information
* @param newReplicas The new replica list
* @return The new directory list
* @throws IllegalArgumentException If currentReplicas and currentDirectories have different lengths,
* or if there are duplicate broker IDs in the replica lists
*/
public static List<Uuid> createDirectoriesFrom(int[] currentReplicas, Uuid[] currentDirectories, List<Integer> newReplicas) {
if (currentReplicas == null) currentReplicas = new int[0];
if (currentDirectories == null) currentDirectories = new Uuid[0];
Map<Integer, Uuid> assignments = createAssignmentMap(currentReplicas, currentDirectories);
List<Uuid> consolidated = new ArrayList<>(newReplicas.size());
for (int newReplica : newReplicas) {
Uuid newDirectory = assignments.getOrDefault(newReplica, UNASSIGNED);
consolidated.add(newDirectory);
}
return consolidated;
}
/**
* Build a mapping from replica to directory based on two lists of the same size and order.
* @param replicas The replicas, represented by the broker IDs
* @param directories The directory information
* @return A map, linking each replica to its assigned directory
* @throws IllegalArgumentException If replicas and directories have different lengths,
* or if there are duplicate broker IDs in the replica list
*/
public static Map<Integer, Uuid> createAssignmentMap(int[] replicas, Uuid[] directories) {
if (replicas.length != directories.length) {
throw new IllegalArgumentException("The lengths for replicas and directories do not match.");
}
Map<Integer, Uuid> assignments = new HashMap<>();
for (int i = 0; i < replicas.length; i++) {
int brokerId = replicas[i];
Uuid directory = directories[i];
if (assignments.put(brokerId, directory) != null) {
throw new IllegalArgumentException("Duplicate broker ID in assignment");
}
}
return assignments;
}
/**
* Create an array with the specified number of entries set to {@link #UNASSIGNED}.
*/
public static Uuid[] unassignedArray(int length) {
return array(length, UNASSIGNED);
}
/**
* Create an array with the specified number of entries set to {@link #MIGRATING}.
*/
public static Uuid[] migratingArray(int length) {
return array(length, MIGRATING);
}
/**
* Create an array with the specified number of entries set to the specified value.
*/
private static Uuid[] array(int length, Uuid value) {
Uuid[] array = new Uuid[length];
Arrays.fill(array, value);
return array;
}
/**
* Check if a directory is online, given a sorted list of online directories.
* @param dir The directory to check
* @param sortedOnlineDirs The sorted list of online directories
* @return true if the directory is considered online, false otherwise
*/
public static boolean isOnline(Uuid dir, List<Uuid> sortedOnlineDirs) {
if (UNASSIGNED.equals(dir) || MIGRATING.equals(dir)) {
return true;
}
if (LOST.equals(dir)) {
return false;
}
// The only time we should have a size be 0 is if we were at a MV prior to 3.7-IV2
// and the system was upgraded. In this case the original list of directories was purged
// during broker registration so we don't know if the directory is online. We assume
// that a broker will halt if all its log directories are down. Eventually the broker
// will send another registration request with information about all log directories.
// Refer KAFKA-16162 for more information
if (sortedOnlineDirs.isEmpty()) {
return true;
}
return Collections.binarySearch(sortedOnlineDirs, dir) >= 0;
}
}
| apache/kafka | server-common/src/main/java/org/apache/kafka/common/DirectoryId.java |
45,344 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.messenger;
import android.os.SystemClock;
import android.util.SparseArray;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
public class NotificationCenter {
private final static long EXPIRE_NOTIFICATIONS_TIME = 5017;
private static int totalEvents = 1;
public static final int didReceiveNewMessages = totalEvents++;
public static final int updateInterfaces = totalEvents++;
public static final int dialogsNeedReload = totalEvents++;
public static final int closeChats = totalEvents++;
public static final int messagesDeleted = totalEvents++;
public static final int historyCleared = totalEvents++;
public static final int messagesRead = totalEvents++;
public static final int threadMessagesRead = totalEvents++;
public static final int commentsRead = totalEvents++;
public static final int changeRepliesCounter = totalEvents++;
public static final int messagesDidLoad = totalEvents++;
public static final int didLoadSponsoredMessages = totalEvents++;
public static final int didLoadSendAsPeers = totalEvents++;
public static final int updateDefaultSendAsPeer = totalEvents++;
public static final int messagesDidLoadWithoutProcess = totalEvents++;
public static final int loadingMessagesFailed = totalEvents++;
public static final int messageReceivedByAck = totalEvents++;
public static final int messageReceivedByServer = totalEvents++;
public static final int messageReceivedByServer2 = totalEvents++;
public static final int messageSendError = totalEvents++;
public static final int forceImportContactsStart = totalEvents++;
public static final int contactsDidLoad = totalEvents++;
public static final int contactsImported = totalEvents++;
public static final int hasNewContactsToImport = totalEvents++;
public static final int chatDidCreated = totalEvents++;
public static final int chatDidFailCreate = totalEvents++;
public static final int chatInfoDidLoad = totalEvents++;
public static final int chatInfoCantLoad = totalEvents++;
public static final int mediaDidLoad = totalEvents++;
public static final int mediaCountDidLoad = totalEvents++;
public static final int mediaCountsDidLoad = totalEvents++;
public static final int encryptedChatUpdated = totalEvents++;
public static final int messagesReadEncrypted = totalEvents++;
public static final int encryptedChatCreated = totalEvents++;
public static final int dialogPhotosLoaded = totalEvents++;
public static final int reloadDialogPhotos = totalEvents++;
public static final int folderBecomeEmpty = totalEvents++;
public static final int removeAllMessagesFromDialog = totalEvents++;
public static final int notificationsSettingsUpdated = totalEvents++;
public static final int blockedUsersDidLoad = totalEvents++;
public static final int openedChatChanged = totalEvents++;
public static final int didCreatedNewDeleteTask = totalEvents++;
public static final int mainUserInfoChanged = totalEvents++;
public static final int privacyRulesUpdated = totalEvents++;
public static final int updateMessageMedia = totalEvents++;
public static final int replaceMessagesObjects = totalEvents++;
public static final int didSetPasscode = totalEvents++;
public static final int passcodeDismissed = totalEvents++;
public static final int twoStepPasswordChanged = totalEvents++;
public static final int didSetOrRemoveTwoStepPassword = totalEvents++;
public static final int didRemoveTwoStepPassword = totalEvents++;
public static final int replyMessagesDidLoad = totalEvents++;
public static final int didLoadPinnedMessages = totalEvents++;
public static final int newSessionReceived = totalEvents++;
public static final int didReceivedWebpages = totalEvents++;
public static final int didReceivedWebpagesInUpdates = totalEvents++;
public static final int stickersDidLoad = totalEvents++;
public static final int diceStickersDidLoad = totalEvents++;
public static final int featuredStickersDidLoad = totalEvents++;
public static final int featuredEmojiDidLoad = totalEvents++;
public static final int groupStickersDidLoad = totalEvents++;
public static final int messagesReadContent = totalEvents++;
public static final int botInfoDidLoad = totalEvents++;
public static final int userInfoDidLoad = totalEvents++;
public static final int pinnedInfoDidLoad = totalEvents++;
public static final int botKeyboardDidLoad = totalEvents++;
public static final int chatSearchResultsAvailable = totalEvents++;
public static final int chatSearchResultsLoading = totalEvents++;
public static final int musicDidLoad = totalEvents++;
public static final int moreMusicDidLoad = totalEvents++;
public static final int needShowAlert = totalEvents++;
public static final int needShowPlayServicesAlert = totalEvents++;
public static final int didUpdateMessagesViews = totalEvents++;
public static final int needReloadRecentDialogsSearch = totalEvents++;
public static final int peerSettingsDidLoad = totalEvents++;
public static final int wasUnableToFindCurrentLocation = totalEvents++;
public static final int reloadHints = totalEvents++;
public static final int reloadInlineHints = totalEvents++;
public static final int newDraftReceived = totalEvents++;
public static final int recentDocumentsDidLoad = totalEvents++;
public static final int needAddArchivedStickers = totalEvents++;
public static final int archivedStickersCountDidLoad = totalEvents++;
public static final int paymentFinished = totalEvents++;
public static final int channelRightsUpdated = totalEvents++;
public static final int openArticle = totalEvents++;
public static final int articleClosed = totalEvents++;
public static final int updateMentionsCount = totalEvents++;
public static final int didUpdatePollResults = totalEvents++;
public static final int chatOnlineCountDidLoad = totalEvents++;
public static final int videoLoadingStateChanged = totalEvents++;
public static final int newPeopleNearbyAvailable = totalEvents++;
public static final int stopAllHeavyOperations = totalEvents++;
public static final int startAllHeavyOperations = totalEvents++;
public static final int stopSpoilers = totalEvents++;
public static final int startSpoilers = totalEvents++;
public static final int sendingMessagesChanged = totalEvents++;
public static final int didUpdateReactions = totalEvents++;
public static final int didUpdateExtendedMedia = totalEvents++;
public static final int didVerifyMessagesStickers = totalEvents++;
public static final int scheduledMessagesUpdated = totalEvents++;
public static final int newSuggestionsAvailable = totalEvents++;
public static final int didLoadChatInviter = totalEvents++;
public static final int didLoadChatAdmins = totalEvents++;
public static final int historyImportProgressChanged = totalEvents++;
public static final int stickersImportProgressChanged = totalEvents++;
public static final int stickersImportComplete = totalEvents++;
public static final int dialogDeleted = totalEvents++;
public static final int webViewResultSent = totalEvents++;
public static final int voiceTranscriptionUpdate = totalEvents++;
public static final int animatedEmojiDocumentLoaded = totalEvents++;
public static final int recentEmojiStatusesUpdate = totalEvents++;
public static final int updateSearchSettings = totalEvents++;
public static final int updateTranscriptionLock = totalEvents++;
public static final int businessMessagesUpdated = totalEvents++;
public static final int quickRepliesUpdated = totalEvents++;
public static final int quickRepliesDeleted = totalEvents++;
public static final int businessLinksUpdated = totalEvents++;
public static final int businessLinkCreated = totalEvents++;
public static final int needDeleteBusinessLink = totalEvents++;
public static final int messageTranslated = totalEvents++;
public static final int messageTranslating = totalEvents++;
public static final int dialogIsTranslatable = totalEvents++;
public static final int dialogTranslate = totalEvents++;
public static final int didGenerateFingerprintKeyPair = totalEvents++;
public static final int walletPendingTransactionsChanged = totalEvents++;
public static final int walletSyncProgressChanged = totalEvents++;
public static final int httpFileDidLoad = totalEvents++;
public static final int httpFileDidFailedLoad = totalEvents++;
public static final int didUpdateConnectionState = totalEvents++;
public static final int fileUploaded = totalEvents++;
public static final int fileUploadFailed = totalEvents++;
public static final int fileUploadProgressChanged = totalEvents++;
public static final int fileLoadProgressChanged = totalEvents++;
public static final int fileLoaded = totalEvents++;
public static final int fileLoadFailed = totalEvents++;
public static final int filePreparingStarted = totalEvents++;
public static final int fileNewChunkAvailable = totalEvents++;
public static final int filePreparingFailed = totalEvents++;
public static final int dialogsUnreadCounterChanged = totalEvents++;
public static final int messagePlayingProgressDidChanged = totalEvents++;
public static final int messagePlayingDidReset = totalEvents++;
public static final int messagePlayingPlayStateChanged = totalEvents++;
public static final int messagePlayingDidStart = totalEvents++;
public static final int messagePlayingDidSeek = totalEvents++;
public static final int messagePlayingGoingToStop = totalEvents++;
public static final int recordProgressChanged = totalEvents++;
public static final int recordStarted = totalEvents++;
public static final int recordStartError = totalEvents++;
public static final int recordStopped = totalEvents++;
public static final int recordPaused = totalEvents++;
public static final int recordResumed = totalEvents++;
public static final int screenshotTook = totalEvents++;
public static final int albumsDidLoad = totalEvents++;
public static final int audioDidSent = totalEvents++;
public static final int audioRecordTooShort = totalEvents++;
public static final int audioRouteChanged = totalEvents++;
public static final int didStartedCall = totalEvents++;
public static final int groupCallUpdated = totalEvents++;
public static final int groupCallSpeakingUsersUpdated = totalEvents++;
public static final int groupCallScreencastStateChanged = totalEvents++;
public static final int activeGroupCallsUpdated = totalEvents++;
public static final int applyGroupCallVisibleParticipants = totalEvents++;
public static final int groupCallTypingsUpdated = totalEvents++;
public static final int didEndCall = totalEvents++;
public static final int closeInCallActivity = totalEvents++;
public static final int groupCallVisibilityChanged = totalEvents++;
public static final int appDidLogout = totalEvents++;
public static final int configLoaded = totalEvents++;
public static final int needDeleteDialog = totalEvents++;
public static final int newEmojiSuggestionsAvailable = totalEvents++;
public static final int themeUploadedToServer = totalEvents++;
public static final int themeUploadError = totalEvents++;
public static final int dialogFiltersUpdated = totalEvents++;
public static final int filterSettingsUpdated = totalEvents++;
public static final int suggestedFiltersLoaded = totalEvents++;
public static final int updateBotMenuButton = totalEvents++;
public static final int giftsToUserSent = totalEvents++;
public static final int didStartedMultiGiftsSelector = totalEvents++;
public static final int boostedChannelByUser = totalEvents++;
public static final int boostByChannelCreated = totalEvents++;
public static final int didUpdatePremiumGiftStickers = totalEvents++;
public static final int didUpdatePremiumGiftFieldIcon = totalEvents++;
public static final int storiesEnabledUpdate = totalEvents++;
public static final int storiesBlocklistUpdate = totalEvents++;
public static final int storiesLimitUpdate = totalEvents++;
public static final int storiesSendAsUpdate = totalEvents++;
public static final int unconfirmedAuthUpdate = totalEvents++;
public static final int dialogPhotosUpdate = totalEvents++;
public static final int channelRecommendationsLoaded = totalEvents++;
public static final int savedMessagesDialogsUpdate = totalEvents++;
public static final int savedReactionTagsUpdate = totalEvents++;
public static final int userIsPremiumBlockedUpadted = totalEvents++;
public static final int savedMessagesForwarded = totalEvents++;
public static final int emojiKeywordsLoaded = totalEvents++;
public static final int smsJobStatusUpdate = totalEvents++;
public static final int storyQualityUpdate = totalEvents++;
public static final int openBoostForUsersDialog = totalEvents++;
public static final int groupRestrictionsUnlockedByBoosts = totalEvents++;
public static final int chatWasBoostedByUser = totalEvents++;
public static final int groupPackUpdated = totalEvents++;
public static final int timezonesUpdated = totalEvents++;
public static final int customStickerCreated = totalEvents++;
public static final int premiumFloodWaitReceived = totalEvents++;
//global
public static final int pushMessagesUpdated = totalEvents++;
public static final int wallpapersDidLoad = totalEvents++;
public static final int wallpapersNeedReload = totalEvents++;
public static final int didReceiveSmsCode = totalEvents++;
public static final int didReceiveCall = totalEvents++;
public static final int emojiLoaded = totalEvents++;
public static final int invalidateMotionBackground = totalEvents++;
public static final int closeOtherAppActivities = totalEvents++;
public static final int cameraInitied = totalEvents++;
public static final int didReplacedPhotoInMemCache = totalEvents++;
public static final int didSetNewTheme = totalEvents++;
public static final int themeListUpdated = totalEvents++;
public static final int didApplyNewTheme = totalEvents++;
public static final int themeAccentListUpdated = totalEvents++;
public static final int needCheckSystemBarColors = totalEvents++;
public static final int needShareTheme = totalEvents++;
public static final int needSetDayNightTheme = totalEvents++;
public static final int goingToPreviewTheme = totalEvents++;
public static final int locationPermissionGranted = totalEvents++;
public static final int locationPermissionDenied = totalEvents++;
public static final int reloadInterface = totalEvents++;
public static final int suggestedLangpack = totalEvents++;
public static final int didSetNewWallpapper = totalEvents++;
public static final int proxySettingsChanged = totalEvents++;
public static final int proxyCheckDone = totalEvents++;
public static final int proxyChangedByRotation = totalEvents++;
public static final int liveLocationsChanged = totalEvents++;
public static final int newLocationAvailable = totalEvents++;
public static final int liveLocationsCacheChanged = totalEvents++;
public static final int notificationsCountUpdated = totalEvents++;
public static final int playerDidStartPlaying = totalEvents++;
public static final int closeSearchByActiveAction = totalEvents++;
public static final int messagePlayingSpeedChanged = totalEvents++;
public static final int screenStateChanged = totalEvents++;
public static final int didClearDatabase = totalEvents++;
public static final int voipServiceCreated = totalEvents++;
public static final int webRtcMicAmplitudeEvent = totalEvents++;
public static final int webRtcSpeakerAmplitudeEvent = totalEvents++;
public static final int showBulletin = totalEvents++;
public static final int appUpdateAvailable = totalEvents++;
public static final int onDatabaseMigration = totalEvents++;
public static final int onEmojiInteractionsReceived = totalEvents++;
public static final int emojiPreviewThemesChanged = totalEvents++;
public static final int reactionsDidLoad = totalEvents++;
public static final int attachMenuBotsDidLoad = totalEvents++;
public static final int chatAvailableReactionsUpdated = totalEvents++;
public static final int dialogsUnreadReactionsCounterChanged = totalEvents++;
public static final int onDatabaseOpened = totalEvents++;
public static final int onDownloadingFilesChanged = totalEvents++;
public static final int onActivityResultReceived = totalEvents++;
public static final int onRequestPermissionResultReceived = totalEvents++;
public static final int onUserRingtonesUpdated = totalEvents++;
public static final int currentUserPremiumStatusChanged = totalEvents++;
public static final int premiumPromoUpdated = totalEvents++;
public static final int premiumStatusChangedGlobal = totalEvents++;
public static final int currentUserShowLimitReachedDialog = totalEvents++;
public static final int billingProductDetailsUpdated = totalEvents++;
public static final int billingConfirmPurchaseError = totalEvents++;
public static final int premiumStickersPreviewLoaded = totalEvents++;
public static final int userEmojiStatusUpdated = totalEvents++;
public static final int requestPermissions = totalEvents++;
public static final int permissionsGranted = totalEvents++;
public static final int topicsDidLoaded = totalEvents++;
public static final int chatSwithcedToForum = totalEvents++;
public static final int didUpdateGlobalAutoDeleteTimer = totalEvents++;
public static final int onDatabaseReset = totalEvents++;
public static final int wallpaperSettedToUser = totalEvents++;
public static final int storiesUpdated = totalEvents++;
public static final int storiesListUpdated = totalEvents++;
public static final int storiesDraftsUpdated = totalEvents++;
public static final int chatlistFolderUpdate = totalEvents++;
public static final int uploadStoryProgress = totalEvents++;
public static final int uploadStoryEnd = totalEvents++;
public static final int customTypefacesLoaded = totalEvents++;
public static final int stealthModeChanged = totalEvents++;
public static final int onReceivedChannelDifference = totalEvents++;
public static final int storiesReadUpdated = totalEvents++;
public static final int nearEarEvent = totalEvents++;
public static boolean alreadyLogged;
private SparseArray<ArrayList<NotificationCenterDelegate>> observers = new SparseArray<>();
private SparseArray<ArrayList<NotificationCenterDelegate>> removeAfterBroadcast = new SparseArray<>();
private SparseArray<ArrayList<NotificationCenterDelegate>> addAfterBroadcast = new SparseArray<>();
private ArrayList<DelayedPost> delayedPosts = new ArrayList<>(10);
private ArrayList<Runnable> delayedRunnables = new ArrayList<>(10);
private ArrayList<Runnable> delayedRunnablesTmp = new ArrayList<>(10);
private ArrayList<DelayedPost> delayedPostsTmp = new ArrayList<>(10);
private ArrayList<PostponeNotificationCallback> postponeCallbackList = new ArrayList<>(10);
private Runnable checkForExpiredNotifications;
private int broadcasting = 0;
private int animationInProgressCount;
private int animationInProgressPointer = 1;
HashSet<Integer> heavyOperationsCounter = new HashSet<>();
private final SparseArray<AllowedNotifications> allowedNotifications = new SparseArray<>();
public interface NotificationCenterDelegate {
void didReceivedNotification(int id, int account, Object... args);
}
private static class DelayedPost {
private DelayedPost(int id, Object[] args) {
this.id = id;
this.args = args;
}
private int id;
private Object[] args;
}
private int currentAccount;
private int currentHeavyOperationFlags;
private static volatile NotificationCenter[] Instance = new NotificationCenter[UserConfig.MAX_ACCOUNT_COUNT];
private static volatile NotificationCenter globalInstance;
@UiThread
public static NotificationCenter getInstance(int num) {
NotificationCenter localInstance = Instance[num];
if (localInstance == null) {
synchronized (NotificationCenter.class) {
localInstance = Instance[num];
if (localInstance == null) {
Instance[num] = localInstance = new NotificationCenter(num);
}
}
}
return localInstance;
}
@UiThread
public static NotificationCenter getGlobalInstance() {
NotificationCenter localInstance = globalInstance;
if (localInstance == null) {
synchronized (NotificationCenter.class) {
localInstance = globalInstance;
if (localInstance == null) {
globalInstance = localInstance = new NotificationCenter(-1);
}
}
}
return localInstance;
}
public NotificationCenter(int account) {
currentAccount = account;
}
public int setAnimationInProgress(int oldIndex, int[] allowedNotifications) {
return setAnimationInProgress(oldIndex, allowedNotifications, true);
}
public int setAnimationInProgress(int oldIndex, int[] allowedNotifications, boolean stopHeavyOperations) {
onAnimationFinish(oldIndex);
if (heavyOperationsCounter.isEmpty() && stopHeavyOperations) {
getGlobalInstance().postNotificationName(stopAllHeavyOperations, 512);
}
animationInProgressCount++;
animationInProgressPointer++;
if (stopHeavyOperations) {
heavyOperationsCounter.add(animationInProgressPointer);
}
AllowedNotifications notifications = new AllowedNotifications();
notifications.allowedIds = allowedNotifications;
this.allowedNotifications.put(animationInProgressPointer, notifications);
if (checkForExpiredNotifications == null) {
AndroidUtilities.runOnUIThread(checkForExpiredNotifications = this::checkForExpiredNotifications, EXPIRE_NOTIFICATIONS_TIME);
}
return animationInProgressPointer;
}
private void checkForExpiredNotifications() {
checkForExpiredNotifications = null;
if (this.allowedNotifications.size() == 0) {
return;
}
long minTime = Long.MAX_VALUE;
long currentTime = SystemClock.elapsedRealtime();
ArrayList<Integer> expiredIndices = null;
for (int i = 0; i < allowedNotifications.size(); i++) {
AllowedNotifications allowedNotification = allowedNotifications.valueAt(i);
if (currentTime - allowedNotification.time > 1000) {
if (expiredIndices == null) {
expiredIndices = new ArrayList<>();
}
expiredIndices.add(allowedNotifications.keyAt(i));
} else {
minTime = Math.min(allowedNotification.time, minTime);
}
}
if (expiredIndices != null) {
for (int i = 0; i < expiredIndices.size(); i++) {
onAnimationFinish(expiredIndices.get(i));
}
}
if (minTime != Long.MAX_VALUE) {
long time = EXPIRE_NOTIFICATIONS_TIME - (currentTime - minTime);
AndroidUtilities.runOnUIThread(() -> checkForExpiredNotifications = this::checkForExpiredNotifications, Math.max(17, time));
}
}
public void updateAllowedNotifications(int transitionAnimationIndex, int[] allowedNotifications) {
AllowedNotifications notifications = this.allowedNotifications.get(transitionAnimationIndex);
if (notifications != null) {
notifications.allowedIds = allowedNotifications;
}
}
public void onAnimationFinish(int index) {
AllowedNotifications allowed = allowedNotifications.get(index);
allowedNotifications.delete(index);
if (allowed != null) {
animationInProgressCount--;
if (!heavyOperationsCounter.isEmpty()) {
heavyOperationsCounter.remove(index);
if (heavyOperationsCounter.isEmpty()) {
NotificationCenter.getGlobalInstance().postNotificationName(startAllHeavyOperations, 512);
}
}
if (animationInProgressCount == 0) {
runDelayedNotifications();
}
}
if (checkForExpiredNotifications != null && allowedNotifications.size() == 0) {
AndroidUtilities.cancelRunOnUIThread(checkForExpiredNotifications);
checkForExpiredNotifications = null;
}
}
public void runDelayedNotifications() {
if (!delayedPosts.isEmpty()) {
delayedPostsTmp.clear();
delayedPostsTmp.addAll(delayedPosts);
delayedPosts.clear();
for (int a = 0; a < delayedPostsTmp.size(); a++) {
DelayedPost delayedPost = delayedPostsTmp.get(a);
postNotificationNameInternal(delayedPost.id, true, delayedPost.args);
}
delayedPostsTmp.clear();
}
if (!delayedRunnables.isEmpty()) {
delayedRunnablesTmp.clear();
delayedRunnablesTmp.addAll(delayedRunnables);
delayedRunnables.clear();
for (int a = 0; a < delayedRunnablesTmp.size(); a++) {
AndroidUtilities.runOnUIThread(delayedRunnablesTmp.get(a));
}
delayedRunnablesTmp.clear();
}
}
public boolean isAnimationInProgress() {
return animationInProgressCount > 0;
}
public int getCurrentHeavyOperationFlags() {
return currentHeavyOperationFlags;
}
public ArrayList<NotificationCenterDelegate> getObservers(int id) {
return observers.get(id);
}
public void postNotificationNameOnUIThread(final int id, final Object... args) {
AndroidUtilities.runOnUIThread(() -> postNotificationName(id, args));
}
public void postNotificationName(int id, Object... args) {
boolean allowDuringAnimation = id == startAllHeavyOperations || id == stopAllHeavyOperations || id == didReplacedPhotoInMemCache || id == closeChats || id == invalidateMotionBackground || id == needCheckSystemBarColors;
ArrayList<Integer> expiredIndices = null;
if (!allowDuringAnimation && allowedNotifications.size() > 0) {
int size = allowedNotifications.size();
int allowedCount = 0;
long currentTime = SystemClock.elapsedRealtime();
for (int i = 0; i < allowedNotifications.size(); i++) {
AllowedNotifications allowedNotification = allowedNotifications.valueAt(i);
if (currentTime - allowedNotification.time > EXPIRE_NOTIFICATIONS_TIME) {
if (expiredIndices == null) {
expiredIndices = new ArrayList<>();
}
expiredIndices.add(allowedNotifications.keyAt(i));
}
int[] allowed = allowedNotification.allowedIds;
if (allowed != null) {
for (int a = 0; a < allowed.length; a++) {
if (allowed[a] == id) {
allowedCount++;
break;
}
}
} else {
break;
}
}
allowDuringAnimation = size == allowedCount;
}
if (id == startAllHeavyOperations) {
Integer flags = (Integer) args[0];
currentHeavyOperationFlags &= ~flags;
} else if (id == stopAllHeavyOperations) {
Integer flags = (Integer) args[0];
currentHeavyOperationFlags |= flags;
}
if (shouldDebounce(id, args) && BuildVars.DEBUG_VERSION) {
postNotificationDebounced(id, args);
} else {
postNotificationNameInternal(id, allowDuringAnimation, args);
}
if (expiredIndices != null) {
for (int i = 0; i < expiredIndices.size(); i++) {
onAnimationFinish(expiredIndices.get(i));
}
}
}
SparseArray<Runnable> alreadyPostedRannubles = new SparseArray<>();
private void postNotificationDebounced(int id, Object[] args) {
int hash = id + (Arrays.hashCode(args) << 16);
if (alreadyPostedRannubles.indexOfKey(hash) >= 0) {
//skip
} else {
Runnable runnable = () -> {
postNotificationNameInternal(id, false, args);
alreadyPostedRannubles.remove(hash);
};
alreadyPostedRannubles.put(hash, runnable);
AndroidUtilities.runOnUIThread(runnable, 250);
}
}
private boolean shouldDebounce(int id, Object[] args) {
return id == updateInterfaces;
}
@UiThread
public void postNotificationNameInternal(int id, boolean allowDuringAnimation, Object... args) {
if (BuildVars.DEBUG_VERSION) {
if (Thread.currentThread() != ApplicationLoader.applicationHandler.getLooper().getThread()) {
throw new RuntimeException("postNotificationName allowed only from MAIN thread");
}
}
if (!allowDuringAnimation && isAnimationInProgress()) {
DelayedPost delayedPost = new DelayedPost(id, args);
delayedPosts.add(delayedPost);
return;
}
if (!postponeCallbackList.isEmpty()) {
for (int i = 0; i < postponeCallbackList.size(); i++) {
if (postponeCallbackList.get(i).needPostpone(id, currentAccount, args)) {
delayedPosts.add(new DelayedPost(id, args));
return;
}
}
}
broadcasting++;
ArrayList<NotificationCenterDelegate> objects = observers.get(id);
if (objects != null && !objects.isEmpty()) {
for (int a = 0; a < objects.size(); a++) {
NotificationCenterDelegate obj = objects.get(a);
obj.didReceivedNotification(id, currentAccount, args);
}
}
broadcasting--;
if (broadcasting == 0) {
if (removeAfterBroadcast.size() != 0) {
for (int a = 0; a < removeAfterBroadcast.size(); a++) {
int key = removeAfterBroadcast.keyAt(a);
ArrayList<NotificationCenterDelegate> arrayList = removeAfterBroadcast.get(key);
for (int b = 0; b < arrayList.size(); b++) {
removeObserver(arrayList.get(b), key);
}
}
removeAfterBroadcast.clear();
}
if (addAfterBroadcast.size() != 0) {
for (int a = 0; a < addAfterBroadcast.size(); a++) {
int key = addAfterBroadcast.keyAt(a);
ArrayList<NotificationCenterDelegate> arrayList = addAfterBroadcast.get(key);
for (int b = 0; b < arrayList.size(); b++) {
addObserver(arrayList.get(b), key);
}
}
addAfterBroadcast.clear();
}
}
}
public void addObserver(NotificationCenterDelegate observer, int id) {
if (BuildVars.DEBUG_VERSION) {
if (Thread.currentThread() != ApplicationLoader.applicationHandler.getLooper().getThread()) {
throw new RuntimeException("addObserver allowed only from MAIN thread");
}
}
if (broadcasting != 0) {
ArrayList<NotificationCenterDelegate> arrayList = addAfterBroadcast.get(id);
if (arrayList == null) {
arrayList = new ArrayList<>();
addAfterBroadcast.put(id, arrayList);
}
arrayList.add(observer);
return;
}
ArrayList<NotificationCenterDelegate> objects = observers.get(id);
if (objects == null) {
observers.put(id, (objects = createArrayForId(id)));
}
if (objects.contains(observer)) {
return;
}
objects.add(observer);
if (BuildVars.DEBUG_VERSION && !alreadyLogged) {
if (objects.size() > 1000) {
alreadyLogged = true;
FileLog.e(new RuntimeException("Total observers more than 1000, need check for memory leak. " + id), true);
}
}
}
private ArrayList<NotificationCenterDelegate> createArrayForId(int id) {
// this notifications often add/remove
// UniqArrayList for fast contains method check
if (id == didReplacedPhotoInMemCache || id == stopAllHeavyOperations || id == startAllHeavyOperations) {
return new UniqArrayList<>();
}
return new ArrayList<>();
}
public void removeObserver(NotificationCenterDelegate observer, int id) {
if (BuildVars.DEBUG_VERSION) {
if (Thread.currentThread() != ApplicationLoader.applicationHandler.getLooper().getThread()) {
throw new RuntimeException("removeObserver allowed only from MAIN thread");
}
}
if (broadcasting != 0) {
ArrayList<NotificationCenterDelegate> arrayList = removeAfterBroadcast.get(id);
if (arrayList == null) {
arrayList = new ArrayList<>();
removeAfterBroadcast.put(id, arrayList);
}
arrayList.add(observer);
return;
}
ArrayList<NotificationCenterDelegate> objects = observers.get(id);
if (objects != null) {
objects.remove(observer);
}
}
public boolean hasObservers(int id) {
return observers.indexOfKey(id) >= 0;
}
public void addPostponeNotificationsCallback(PostponeNotificationCallback callback) {
if (BuildVars.DEBUG_VERSION) {
if (Thread.currentThread() != ApplicationLoader.applicationHandler.getLooper().getThread()) {
throw new RuntimeException("PostponeNotificationsCallback allowed only from MAIN thread");
}
}
if (!postponeCallbackList.contains(callback)) {
postponeCallbackList.add(callback);
}
}
public void removePostponeNotificationsCallback(PostponeNotificationCallback callback) {
if (BuildVars.DEBUG_VERSION) {
if (Thread.currentThread() != ApplicationLoader.applicationHandler.getLooper().getThread()) {
throw new RuntimeException("removePostponeNotificationsCallback allowed only from MAIN thread");
}
}
if (postponeCallbackList.remove(callback)) {
runDelayedNotifications();
}
}
public interface PostponeNotificationCallback {
boolean needPostpone(int id, int currentAccount, Object[] args);
}
public void doOnIdle(Runnable runnable) {
if (isAnimationInProgress()) {
delayedRunnables.add(runnable);
} else {
runnable.run();
}
}
public void removeDelayed(Runnable runnable) {
delayedRunnables.remove(runnable);
}
private static class AllowedNotifications {
int[] allowedIds;
final long time;
private AllowedNotifications() {
time = SystemClock.elapsedRealtime();
}
}
public Runnable listenGlobal(View view, final int id, final Utilities.Callback<Object[]> callback) {
if (view == null || callback == null) {
return () -> {};
}
final NotificationCenterDelegate delegate = (_id, account, args) -> {
if (_id == id) {
callback.run(args);
}
};
final View.OnAttachStateChangeListener viewListener = new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View view) {
NotificationCenter.getGlobalInstance().addObserver(delegate, id);
}
@Override
public void onViewDetachedFromWindow(View view) {
NotificationCenter.getGlobalInstance().removeObserver(delegate, id);
}
};
view.addOnAttachStateChangeListener(viewListener);
return () -> {
view.removeOnAttachStateChangeListener(viewListener);
NotificationCenter.getGlobalInstance().removeObserver(delegate, id);
};
}
public Runnable listen(View view, final int id, final Utilities.Callback<Object[]> callback) {
if (view == null || callback == null) {
return () -> {};
}
final NotificationCenterDelegate delegate = (_id, account, args) -> {
if (_id == id) {
callback.run(args);
}
};
final View.OnAttachStateChangeListener viewListener = new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View view) {
addObserver(delegate, id);
}
@Override
public void onViewDetachedFromWindow(View view) {
removeObserver(delegate, id);
}
};
view.addOnAttachStateChangeListener(viewListener);
return () -> {
view.removeOnAttachStateChangeListener(viewListener);
removeObserver(delegate, id);
};
}
public static void listenEmojiLoading(View view) {
getGlobalInstance().listenGlobal(view, NotificationCenter.emojiLoaded, args -> view.invalidate());
}
public void listenOnce(int id, Runnable callback) {
final NotificationCenterDelegate[] observer = new NotificationCenterDelegate[1];
observer[0] = (nid, account, args) -> {
if (nid == id && observer[0] != null) {
if (callback != null) {
callback.run();
}
removeObserver(observer[0], id);
observer[0] = null;
}
};
addObserver(observer[0], id);
}
private class UniqArrayList<T> extends ArrayList<T> {
HashSet<T> set = new HashSet<>();
@Override
public boolean add(T t) {
if (set.add(t)) {
return super.add(t);
}
return false;
}
@Override
public void add(int index, T element) {
if (set.add(element)) {
super.add(index, element);
}
}
@Override
public boolean addAll(@NonNull Collection<? extends T> c) {
boolean modified = false;
for (T t : c) {
if (add(t)) {
modified = true;
}
}
return modified;
}
@Override
public boolean addAll(int index, @NonNull Collection<? extends T> c) {
throw new UnsupportedOperationException();
}
@Override
public T remove(int index) {
T t = super.remove(index);
if (t != null) {
set.remove(t);
}
return t;
}
@Override
public boolean remove(@Nullable Object o) {
if (set.remove(o)) {
return super.remove(o);
}
return false;
}
@Override
public boolean removeAll(@NonNull Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean contains(@Nullable Object o) {
return set.contains(o);
}
@Override
public void clear() {
set.clear();
super.clear();
}
}
}
| DrKLO/Telegram | TMessagesProj/src/main/java/org/telegram/messenger/NotificationCenter.java |
45,345 | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.xdebugger.impl;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.filters.HyperlinkInfo;
import com.intellij.execution.filters.OpenFileHyperlinkInfo;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.*;
import com.intellij.icons.AllIcons;
import com.intellij.ide.DataManager;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationGroup;
import com.intellij.notification.NotificationGroupManager;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.ui.AppUIUtil;
import com.intellij.util.EventDispatcher;
import com.intellij.util.SmartList;
import com.intellij.util.concurrency.annotations.RequiresReadLock;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.*;
import com.intellij.xdebugger.breakpoints.*;
import com.intellij.xdebugger.frame.XExecutionStack;
import com.intellij.xdebugger.frame.XStackFrame;
import com.intellij.xdebugger.frame.XSuspendContext;
import com.intellij.xdebugger.frame.XValueMarkerProvider;
import com.intellij.xdebugger.impl.actions.XDebuggerActions;
import com.intellij.xdebugger.impl.breakpoints.*;
import com.intellij.xdebugger.impl.evaluate.quick.common.ValueLookupManager;
import com.intellij.xdebugger.impl.frame.XValueMarkers;
import com.intellij.xdebugger.impl.frame.XWatchesViewImpl;
import com.intellij.xdebugger.impl.inline.DebuggerInlayListener;
import com.intellij.xdebugger.impl.inline.InlineDebugRenderer;
import com.intellij.xdebugger.impl.settings.XDebuggerSettingManagerImpl;
import com.intellij.xdebugger.impl.ui.XDebugSessionData;
import com.intellij.xdebugger.impl.ui.XDebugSessionTab;
import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants;
import com.intellij.xdebugger.impl.util.BringDebuggeeInForegroundUtilsKt;
import com.intellij.xdebugger.stepping.XSmartStepIntoHandler;
import com.intellij.xdebugger.stepping.XSmartStepIntoVariant;
import kotlinx.coroutines.flow.FlowKt;
import kotlinx.coroutines.flow.StateFlow;
import kotlinx.coroutines.flow.StateFlowKt;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public final class XDebugSessionImpl implements XDebugSession {
private static final Logger LOG = Logger.getInstance(XDebugSessionImpl.class);
private static final Logger PERFORMANCE_LOG = Logger.getInstance("#com.intellij.xdebugger.impl.XDebugSessionImpl.performance");
private static final NotificationGroup BP_NOTIFICATION_GROUP = NotificationGroupManager.getInstance().getNotificationGroup("Breakpoint hit");
// TODO[eldar] needed to workaround nullable myAlternativeSourceHandler.
private static final StateFlow<Boolean> ALWAYS_FALSE_STATE = FlowKt.asStateFlow(StateFlowKt.MutableStateFlow(false));
private XDebugProcess myDebugProcess;
private final Map<XBreakpoint<?>, CustomizedBreakpointPresentation> myRegisteredBreakpoints = new HashMap<>();
private final Set<XBreakpoint<?>> myInactiveSlaveBreakpoints = Collections.synchronizedSet(new HashSet<>());
private boolean myBreakpointsDisabled;
private final XDebuggerManagerImpl myDebuggerManager;
private final XDebuggerExecutionPointManager myExecutionPointManager;
private Disposable myBreakpointListenerDisposable;
private XSuspendContext mySuspendContext;
private XExecutionStack myCurrentExecutionStack;
private XStackFrame myCurrentStackFrame;
private @Nullable XAlternativeSourceHandler myAlternativeSourceHandler;
private boolean myIsTopFrame;
private volatile XStackFrame myTopStackFrame;
private final AtomicBoolean myPaused = new AtomicBoolean();
private XValueMarkers<?, ?> myValueMarkers;
private @Nls final String mySessionName;
private @Nullable XDebugSessionTab mySessionTab;
private @NotNull final XDebugSessionData mySessionData;
private final AtomicReference<Pair<XBreakpoint<?>, XSourcePosition>> myActiveNonLineBreakpoint = new AtomicReference<>();
private final EventDispatcher<XDebugSessionListener> myDispatcher = EventDispatcher.create(XDebugSessionListener.class);
private final Project myProject;
private final @Nullable ExecutionEnvironment myEnvironment;
private final AtomicBoolean myStopped = new AtomicBoolean();
private boolean myPauseActionSupported;
private boolean myReadOnly = false;
private final AtomicBoolean myShowTabOnSuspend;
private final List<AnAction> myRestartActions = new SmartList<>();
private final List<AnAction> myExtraStopActions = new SmartList<>();
private final List<AnAction> myExtraActions = new SmartList<>();
private ConsoleView myConsoleView;
private final Icon myIcon;
private volatile boolean breakpointsInitialized;
private long myUserRequestStart;
private String myUserRequestAction;
public XDebugSessionImpl(@NotNull ExecutionEnvironment environment, @NotNull XDebuggerManagerImpl debuggerManager) {
this(environment, debuggerManager, environment.getRunProfile().getName(), environment.getRunProfile().getIcon(), false, null);
}
public XDebugSessionImpl(@Nullable ExecutionEnvironment environment,
@NotNull XDebuggerManagerImpl debuggerManager,
@NotNull @Nls String sessionName,
@Nullable Icon icon,
boolean showTabOnSuspend,
@Nullable RunContentDescriptor contentToReuse) {
myEnvironment = environment;
mySessionName = sessionName;
myDebuggerManager = debuggerManager;
myShowTabOnSuspend = new AtomicBoolean(showTabOnSuspend);
myProject = debuggerManager.getProject();
myExecutionPointManager = debuggerManager.getExecutionPointManager();
ValueLookupManager.getInstance(myProject).startListening();
DebuggerInlayListener.getInstance(myProject).startListening();
myIcon = icon;
XDebugSessionData oldSessionData = null;
if (contentToReuse == null) {
contentToReuse = environment != null ? environment.getContentToReuse() : null;
}
if (contentToReuse != null) {
JComponent component = contentToReuse.getComponent();
if (component != null) {
oldSessionData = XDebugSessionData.DATA_KEY.getData(DataManager.getInstance().getDataContext(component));
}
}
String currentConfigurationName = computeConfigurationName();
if (oldSessionData == null || !oldSessionData.getConfigurationName().equals(currentConfigurationName)) {
List<XExpression> watchExpressions = myDebuggerManager.getWatchesManager().getWatches(currentConfigurationName);
oldSessionData = new XDebugSessionData(watchExpressions, currentConfigurationName);
}
mySessionData = oldSessionData;
}
@Override
@NotNull
public String getSessionName() {
return mySessionName;
}
@Override
@NotNull
public RunContentDescriptor getRunContentDescriptor() {
assertSessionTabInitialized();
//noinspection ConstantConditions
return mySessionTab.getRunContentDescriptor();
}
private void assertSessionTabInitialized() {
if (myShowTabOnSuspend.get()) {
LOG.error("Debug tool window isn't shown yet because debug process isn't suspended");
}
else {
LOG.assertTrue(mySessionTab != null, "Debug tool window not initialized yet!");
}
}
@Override
public void setPauseActionSupported(final boolean isSupported) {
myPauseActionSupported = isSupported;
}
public boolean isReadOnly() {
return myReadOnly;
}
public void setReadOnly(boolean readOnly) {
myReadOnly = readOnly;
}
@NotNull
public List<AnAction> getRestartActions() {
return myRestartActions;
}
public void addRestartActions(AnAction... restartActions) {
if (restartActions != null) {
Collections.addAll(myRestartActions, restartActions);
}
}
@NotNull
public List<AnAction> getExtraActions() {
return myExtraActions;
}
public void addExtraActions(AnAction... extraActions) {
if (extraActions != null) {
Collections.addAll(myExtraActions, extraActions);
}
}
public List<AnAction> getExtraStopActions() {
return myExtraStopActions;
}
// used externally
@SuppressWarnings("unused")
public void addExtraStopActions(AnAction... extraStopActions) {
if (extraStopActions != null) {
Collections.addAll(myExtraStopActions, extraStopActions);
}
}
@Override
public void rebuildViews() {
myDispatcher.getMulticaster().settingsChanged();
}
@Override
@Nullable
public RunProfile getRunProfile() {
return myEnvironment != null ? myEnvironment.getRunProfile() : null;
}
public boolean isPauseActionSupported() {
return myPauseActionSupported;
}
@Override
@NotNull
public Project getProject() {
return myDebuggerManager.getProject();
}
@Override
@NotNull
public XDebugProcess getDebugProcess() {
return myDebugProcess;
}
@Override
public boolean isSuspended() {
return myPaused.get() && mySuspendContext != null;
}
@Override
public boolean isPaused() {
return myPaused.get();
}
@Override
public @Nullable XStackFrame getCurrentStackFrame() {
return myCurrentStackFrame;
}
public @Nullable XExecutionStack getCurrentExecutionStack() {
return myCurrentExecutionStack;
}
@Override
public @Nullable XSuspendContext getSuspendContext() {
return mySuspendContext;
}
@Override
public @Nullable XSourcePosition getCurrentPosition() {
return getFrameSourcePosition(myCurrentStackFrame);
}
@Override
public @Nullable XSourcePosition getTopFramePosition() {
return getFrameSourcePosition(myTopStackFrame);
}
public @Nullable XSourcePosition getFrameSourcePosition(@Nullable XStackFrame frame) {
return getFrameSourcePosition(frame, getCurrentSourceKind());
}
public @Nullable XSourcePosition getFrameSourcePosition(@Nullable XStackFrame frame, @NotNull XSourceKind sourceKind) {
if (frame == null) return null;
return switch (sourceKind) {
case MAIN -> frame.getSourcePosition();
case ALTERNATIVE -> myAlternativeSourceHandler != null ? myAlternativeSourceHandler.getAlternativePosition(frame) : null;
};
}
public @NotNull XSourceKind getCurrentSourceKind() {
StateFlow<@NotNull Boolean> state = getAlternativeSourceKindState();
return state.getValue() ? XSourceKind.ALTERNATIVE : XSourceKind.MAIN;
}
@NotNull StateFlow<@NotNull Boolean> getAlternativeSourceKindState() {
return myAlternativeSourceHandler != null ? myAlternativeSourceHandler.getAlternativeSourceKindState() : ALWAYS_FALSE_STATE;
}
void init(@NotNull XDebugProcess process, @Nullable RunContentDescriptor contentToReuse) {
LOG.assertTrue(myDebugProcess == null);
myDebugProcess = process;
myAlternativeSourceHandler = myDebugProcess.getAlternativeSourceHandler();
myExecutionPointManager.setAlternativeSourceKindFlow(getAlternativeSourceKindState());
if (myDebugProcess.checkCanInitBreakpoints()) {
initBreakpoints();
}
if (myDebugProcess instanceof XDebugProcessDebuggeeInForeground debuggeeInForeground &&
debuggeeInForeground.isBringingToForegroundApplicable()) {
BringDebuggeeInForegroundUtilsKt.start(debuggeeInForeground, this, 1000);
}
myDebugProcess.getProcessHandler().addProcessListener(new ProcessAdapter() {
@Override
public void processTerminated(@NotNull final ProcessEvent event) {
stopImpl();
myDebugProcess.getProcessHandler().removeProcessListener(this);
}
});
//todo make 'createConsole()' method return ConsoleView
myConsoleView = (ConsoleView)myDebugProcess.createConsole();
if (!myShowTabOnSuspend.get()) {
initSessionTab(contentToReuse);
}
}
public void reset() {
breakpointsInitialized = false;
removeBreakpointListeners();
unsetPaused();
clearPausedData();
rebuildViews();
}
@RequiresReadLock
@Override
public void initBreakpoints() {
LOG.assertTrue(!breakpointsInitialized);
breakpointsInitialized = true;
disableSlaveBreakpoints();
processAllBreakpoints(true, false);
if (myBreakpointListenerDisposable == null) {
myBreakpointListenerDisposable = Disposer.newDisposable();
Disposer.register(myProject, myBreakpointListenerDisposable);
MessageBusConnection busConnection = myProject.getMessageBus().connect(myBreakpointListenerDisposable);
busConnection.subscribe(XBreakpointListener.TOPIC, new MyBreakpointListener());
busConnection.subscribe(XDependentBreakpointListener.TOPIC, new MyDependentBreakpointListener());
}
}
@Override
public ConsoleView getConsoleView() {
return myConsoleView;
}
@Nullable
public XDebugSessionTab getSessionTab() {
return mySessionTab;
}
@Override
public RunnerLayoutUi getUI() {
assertSessionTabInitialized();
assert mySessionTab != null;
return mySessionTab.getUi();
}
private void initSessionTab(@Nullable RunContentDescriptor contentToReuse) {
mySessionTab = XDebugSessionTab.create(this, myIcon, myEnvironment, contentToReuse);
myDebugProcess.sessionInitialized();
addSessionListener(new XDebugSessionListener() {
@Override
public void sessionPaused() {
updateActions();
}
@Override
public void sessionResumed() {
updateActions();
}
@Override
public void sessionStopped() {
updateActions();
}
@Override
public void stackFrameChanged() {
updateActions();
}
private void updateActions() {
UIUtil.invokeLaterIfNeeded(() -> mySessionTab.getUi().updateActionsNow());
}
});
}
@NotNull
public XDebugSessionData getSessionData() {
return mySessionData;
}
private void disableSlaveBreakpoints() {
Set<XBreakpoint<?>> slaveBreakpoints = myDebuggerManager.getBreakpointManager().getDependentBreakpointManager().getAllSlaveBreakpoints();
if (slaveBreakpoints.isEmpty()) {
return;
}
Set<XBreakpointType<?, ?>> breakpointTypes = new HashSet<>();
for (XBreakpointHandler<?> handler : myDebugProcess.getBreakpointHandlers()) {
breakpointTypes.add(getBreakpointTypeClass(handler));
}
for (XBreakpoint<?> slaveBreakpoint : slaveBreakpoints) {
if (breakpointTypes.contains(slaveBreakpoint.getType())) {
myInactiveSlaveBreakpoints.add(slaveBreakpoint);
}
}
}
public void showSessionTab() {
RunContentDescriptor descriptor = getRunContentDescriptor();
RunContentManager.getInstance(getProject()).showRunContent(DefaultDebugExecutor.getDebugExecutorInstance(), descriptor);
}
@Nullable
public XValueMarkers<?, ?> getValueMarkers() {
if (myValueMarkers == null) {
XValueMarkerProvider<?, ?> provider = myDebugProcess.createValueMarkerProvider();
if (provider != null) {
myValueMarkers = XValueMarkers.createValueMarkers(provider);
}
}
return myValueMarkers;
}
@SuppressWarnings("unchecked") //need to compile under 1.8, please do not remove before checking
private static XBreakpointType getBreakpointTypeClass(final XBreakpointHandler handler) {
return XDebuggerUtil.getInstance().findBreakpointType(handler.getBreakpointTypeClass());
}
private <B extends XBreakpoint<?>> void processBreakpoints(final XBreakpointHandler<B> handler,
boolean register,
final boolean temporary) {
Collection<? extends B> breakpoints = myDebuggerManager.getBreakpointManager().getBreakpoints(handler.getBreakpointTypeClass());
for (B b : breakpoints) {
handleBreakpoint(handler, b, register, temporary);
}
}
private <B extends XBreakpoint<?>> void handleBreakpoint(final XBreakpointHandler<B> handler, final B b, final boolean register,
final boolean temporary) {
if (register) {
boolean active = ReadAction.compute(() -> isBreakpointActive(b));
if (active) {
synchronized (myRegisteredBreakpoints) {
myRegisteredBreakpoints.put(b, new CustomizedBreakpointPresentation());
if (b instanceof XLineBreakpoint) {
updateBreakpointPresentation((XLineBreakpoint)b, b.getType().getPendingIcon(), null);
}
}
handler.registerBreakpoint(b);
}
}
else {
boolean removed;
synchronized (myRegisteredBreakpoints) {
removed = myRegisteredBreakpoints.remove(b) != null;
}
if (removed) {
handler.unregisterBreakpoint(b, temporary);
}
}
}
@Nullable
public CustomizedBreakpointPresentation getBreakpointPresentation(@NotNull XBreakpoint<?> breakpoint) {
synchronized (myRegisteredBreakpoints) {
return myRegisteredBreakpoints.get(breakpoint);
}
}
private void processAllHandlers(final XBreakpoint<?> breakpoint, final boolean register) {
for (XBreakpointHandler<?> handler : myDebugProcess.getBreakpointHandlers()) {
processBreakpoint(breakpoint, handler, register);
}
}
private <B extends XBreakpoint<?>> void processBreakpoint(final XBreakpoint<?> breakpoint,
final XBreakpointHandler<B> handler,
boolean register) {
XBreakpointType<?, ?> type = breakpoint.getType();
if (handler.getBreakpointTypeClass().equals(type.getClass())) {
//noinspection unchecked
B b = (B)breakpoint;
handleBreakpoint(handler, b, register, false);
}
}
@RequiresReadLock
public boolean isBreakpointActive(@NotNull XBreakpoint<?> b) {
return !areBreakpointsMuted() && b.isEnabled() && !isInactiveSlaveBreakpoint(b) && !((XBreakpointBase<?, ?, ?>)b).isDisposed();
}
@Override
public boolean areBreakpointsMuted() {
return mySessionData.isBreakpointsMuted();
}
@Override
public void addSessionListener(@NotNull XDebugSessionListener listener, @NotNull Disposable parentDisposable) {
myDispatcher.addListener(listener, parentDisposable);
}
@Override
public void addSessionListener(@NotNull final XDebugSessionListener listener) {
myDispatcher.addListener(listener);
}
@Override
public void removeSessionListener(@NotNull final XDebugSessionListener listener) {
myDispatcher.removeListener(listener);
}
@RequiresReadLock
@Override
public void setBreakpointMuted(boolean muted) {
if (areBreakpointsMuted() == muted) return;
mySessionData.setBreakpointsMuted(muted);
if (!myBreakpointsDisabled) {
processAllBreakpoints(!muted, muted);
}
myDebuggerManager.getBreakpointManager().getLineBreakpointManager().queueAllBreakpointsUpdate();
myDispatcher.getMulticaster().breakpointsMuted(muted);
}
@Override
public void stepOver(final boolean ignoreBreakpoints) {
rememberUserActionStart(XDebuggerActions.STEP_OVER);
if (!myDebugProcess.checkCanPerformCommands()) return;
if (ignoreBreakpoints) {
setBreakpointsDisabledTemporarily(true);
}
myDebugProcess.startStepOver(doResume());
}
@Override
public void stepInto() {
rememberUserActionStart(XDebuggerActions.STEP_INTO);
if (!myDebugProcess.checkCanPerformCommands()) return;
myDebugProcess.startStepInto(doResume());
}
@Override
public void stepOut() {
rememberUserActionStart(XDebuggerActions.STEP_OUT);
if (!myDebugProcess.checkCanPerformCommands()) return;
myDebugProcess.startStepOut(doResume());
}
@Override
public <V extends XSmartStepIntoVariant> void smartStepInto(XSmartStepIntoHandler<V> handler, V variant) {
rememberUserActionStart(XDebuggerActions.SMART_STEP_INTO);
if (!myDebugProcess.checkCanPerformCommands()) return;
final XSuspendContext context = doResume();
handler.startStepInto(variant, context);
}
@Override
public void forceStepInto() {
rememberUserActionStart(XDebuggerActions.FORCE_STEP_INTO);
if (!myDebugProcess.checkCanPerformCommands()) return;
myDebugProcess.startForceStepInto(doResume());
}
@Override
public void runToPosition(@NotNull final XSourcePosition position, final boolean ignoreBreakpoints) {
rememberUserActionStart(XDebuggerActions.RUN_TO_CURSOR);
if (!myDebugProcess.checkCanPerformCommands()) return;
if (ignoreBreakpoints) {
setBreakpointsDisabledTemporarily(true);
}
myDebugProcess.runToPosition(position, doResume());
}
@Override
public void pause() {
rememberUserActionStart(XDebuggerActions.PAUSE);
if (!myDebugProcess.checkCanPerformCommands()) return;
myDebugProcess.startPausing();
}
@RequiresReadLock
private void processAllBreakpoints(final boolean register, final boolean temporary) {
for (XBreakpointHandler<?> handler : myDebugProcess.getBreakpointHandlers()) {
processBreakpoints(handler, register, temporary);
}
}
private void setBreakpointsDisabledTemporarily(boolean disabled) {
ApplicationManager.getApplication().runReadAction(() -> {
if (myBreakpointsDisabled == disabled) return;
myBreakpointsDisabled = disabled;
if (!areBreakpointsMuted()) {
processAllBreakpoints(!disabled, disabled);
}
});
}
@Override
public void resume() {
if (!myDebugProcess.checkCanPerformCommands()) return;
myDebugProcess.resume(doResume());
}
@Nullable
private XSuspendContext doResume() {
if (!myPaused.getAndSet(false)) {
return null;
}
myDispatcher.getMulticaster().beforeSessionResume();
XSuspendContext context = mySuspendContext;
clearPausedData();
UIUtil.invokeLaterIfNeeded(() -> {
if (mySessionTab != null) {
mySessionTab.getUi().clearAttractionBy(XDebuggerUIConstants.LAYOUT_VIEW_BREAKPOINT_CONDITION);
}
});
myDispatcher.getMulticaster().sessionResumed();
return context;
}
private void clearPausedData() {
mySuspendContext = null;
myCurrentExecutionStack = null;
myCurrentStackFrame = null;
myTopStackFrame = null;
clearActiveNonLineBreakpoint();
updateExecutionPosition();
}
@Override
public void updateExecutionPosition() {
updateExecutionPosition(getCurrentSourceKind());
}
private void updateExecutionPosition(@NotNull XSourceKind navigationSourceKind) {
// allowed only for the active session
if (myDebuggerManager.getCurrentSession() == this) {
boolean isTopFrame = isTopFrameSelected();
XSourcePosition mainSourcePosition = getFrameSourcePosition(myCurrentStackFrame, XSourceKind.MAIN);
XSourcePosition alternativeSourcePosition = getFrameSourcePosition(myCurrentStackFrame, XSourceKind.ALTERNATIVE);
myExecutionPointManager.setExecutionPoint(mainSourcePosition, alternativeSourcePosition, isTopFrame, navigationSourceKind);
updateExecutionPointGutterIconRenderer();
}
}
public boolean isTopFrameSelected() {
return myCurrentExecutionStack != null && myIsTopFrame;
}
@Override
public void showExecutionPoint() {
if (mySuspendContext != null) {
XExecutionStack executionStack = mySuspendContext.getActiveExecutionStack();
if (executionStack != null) {
XStackFrame topFrame = executionStack.getTopFrame();
if (topFrame != null) {
setCurrentStackFrame(executionStack, topFrame, true);
myExecutionPointManager.showExecutionPosition();
}
}
}
}
@Override
public void setCurrentStackFrame(@NotNull XExecutionStack executionStack, @NotNull XStackFrame frame, boolean isTopFrame) {
if (mySuspendContext == null) return;
boolean frameChanged = myCurrentStackFrame != frame;
myCurrentExecutionStack = executionStack;
myCurrentStackFrame = frame;
myIsTopFrame = isTopFrame;
if (frameChanged) {
myDispatcher.getMulticaster().stackFrameChanged();
}
activateSession(frameChanged);
}
void activateSession(boolean forceUpdateExecutionPosition) {
boolean sessionChanged = myDebuggerManager.setCurrentSession(this);
if (sessionChanged || forceUpdateExecutionPosition) {
updateExecutionPosition();
}
else {
myExecutionPointManager.showExecutionPosition();
}
}
public XBreakpoint<?> getActiveNonLineBreakpoint() {
Pair<XBreakpoint<?>, XSourcePosition> pair = myActiveNonLineBreakpoint.get();
if (pair != null) {
XSourcePosition breakpointPosition = pair.getSecond();
XSourcePosition position = getTopFramePosition();
if (breakpointPosition == null ||
(position != null &&
!(breakpointPosition.getFile().equals(position.getFile()) && breakpointPosition.getLine() == position.getLine()))) {
return pair.getFirst();
}
}
return null;
}
public void checkActiveNonLineBreakpointOnRemoval(@NotNull XBreakpoint<?> removedBreakpoint) {
Pair<XBreakpoint<?>, XSourcePosition> pair = myActiveNonLineBreakpoint.get();
if (pair != null && pair.getFirst() == removedBreakpoint) {
clearActiveNonLineBreakpoint();
updateExecutionPointGutterIconRenderer();
}
}
private void clearActiveNonLineBreakpoint() {
myActiveNonLineBreakpoint.set(null);
}
void updateExecutionPointGutterIconRenderer() {
if (myDebuggerManager.getCurrentSession() == this) {
boolean isTopFrame = isTopFrameSelected();
GutterIconRenderer renderer = getPositionIconRenderer(isTopFrame);
myExecutionPointManager.setGutterIconRenderer(renderer);
}
}
@Nullable
private GutterIconRenderer getPositionIconRenderer(boolean isTopFrame) {
if (!isTopFrame) {
return null;
}
XBreakpoint<?> activeNonLineBreakpoint = getActiveNonLineBreakpoint();
if (activeNonLineBreakpoint != null) {
return ((XBreakpointBase<?, ?, ?>)activeNonLineBreakpoint).createGutterIconRenderer();
}
if (myCurrentExecutionStack != null) {
return myCurrentExecutionStack.getExecutionLineIconRenderer();
}
return null;
}
@Override
public void updateBreakpointPresentation(@NotNull final XLineBreakpoint<?> breakpoint,
@Nullable final Icon icon,
@Nullable final String errorMessage) {
CustomizedBreakpointPresentation presentation;
synchronized (myRegisteredBreakpoints) {
presentation = myRegisteredBreakpoints.get(breakpoint);
if (presentation == null ||
(Comparing.equal(presentation.getIcon(), icon) && Comparing.strEqual(presentation.getErrorMessage(), errorMessage))) {
return;
}
presentation.setErrorMessage(errorMessage);
presentation.setIcon(icon);
long timestamp = presentation.getTimestamp();
if (timestamp != 0 && XDebuggerUtilImpl.getVerifiedIcon(breakpoint).equals(icon)) {
long delay = System.currentTimeMillis() - timestamp;
presentation.setTimestamp(0);
BreakpointsUsageCollector.reportBreakpointVerified(breakpoint, delay);
}
}
XBreakpointManagerImpl debuggerManager = myDebuggerManager.getBreakpointManager();
debuggerManager.getLineBreakpointManager().queueBreakpointUpdate(breakpoint, () -> debuggerManager.fireBreakpointPresentationUpdated(breakpoint, this));
}
@Override
public void setBreakpointVerified(@NotNull XLineBreakpoint<?> breakpoint) {
updateBreakpointPresentation(breakpoint, XDebuggerUtilImpl.getVerifiedIcon(breakpoint), null);
}
@Override
public void setBreakpointInvalid(@NotNull XLineBreakpoint<?> breakpoint, @Nullable String errorMessage) {
updateBreakpointPresentation(breakpoint, AllIcons.Debugger.Db_invalid_breakpoint, errorMessage);
}
@Override
public boolean breakpointReached(@NotNull final XBreakpoint<?> breakpoint, @Nullable String evaluatedLogExpression,
@NotNull XSuspendContext suspendContext) {
return breakpointReached(breakpoint, evaluatedLogExpression, suspendContext, true);
}
public void breakpointReachedNoProcessing(@NotNull final XBreakpoint<?> breakpoint, @NotNull XSuspendContext suspendContext) {
breakpointReached(breakpoint, null, suspendContext, false);
}
private boolean breakpointReached(@NotNull final XBreakpoint<?> breakpoint, @Nullable String evaluatedLogExpression,
@NotNull XSuspendContext suspendContext, boolean doProcessing) {
if (doProcessing) {
if (breakpoint.isLogMessage()) {
XSourcePosition position = breakpoint.getSourcePosition();
OpenFileHyperlinkInfo hyperlinkInfo =
position != null ? new OpenFileHyperlinkInfo(myProject, position.getFile(), position.getLine()) : null;
printMessage(XDebuggerBundle.message("xbreakpoint.reached.text") + " ", XBreakpointUtil.getShortText(breakpoint), hyperlinkInfo);
}
if (breakpoint.isLogStack()) {
myDebugProcess.logStack(suspendContext, this);
}
if (evaluatedLogExpression != null) {
printMessage(evaluatedLogExpression, null, null);
}
processDependencies(breakpoint);
if (breakpoint.getSuspendPolicy() == SuspendPolicy.NONE) {
return false;
}
}
BP_NOTIFICATION_GROUP
.createNotification(XDebuggerBundle.message("xdebugger.breakpoint.reached"), MessageType.INFO)
.notify(getProject());
if (!(breakpoint instanceof XLineBreakpoint) || ((XLineBreakpoint)breakpoint).getType().canBeHitInOtherPlaces()) {
// precompute source position for faster access later
myActiveNonLineBreakpoint.set(Pair.create(breakpoint, breakpoint.getSourcePosition()));
}
else {
myActiveNonLineBreakpoint.set(null);
}
// set this session active on breakpoint, update execution position will be called inside positionReached
myDebuggerManager.setCurrentSession(this);
positionReachedInternal(suspendContext, true);
if (doProcessing && breakpoint instanceof XLineBreakpoint<?> && ((XLineBreakpoint<?>)breakpoint).isTemporary()) {
handleTemporaryBreakpointHit(breakpoint);
}
return true;
}
private void handleTemporaryBreakpointHit(final XBreakpoint<?> breakpoint) {
addSessionListener(new XDebugSessionListener() {
private void removeBreakpoint() {
XDebuggerUtil.getInstance().removeBreakpoint(myProject, breakpoint);
removeSessionListener(this);
}
@Override
public void sessionResumed() {
removeBreakpoint();
}
@Override
public void sessionStopped() {
removeBreakpoint();
}
});
}
public void processDependencies(final XBreakpoint<?> breakpoint) {
XDependentBreakpointManager dependentBreakpointManager = myDebuggerManager.getBreakpointManager().getDependentBreakpointManager();
if (!dependentBreakpointManager.isMasterOrSlave(breakpoint)) return;
List<XBreakpoint<?>> breakpoints = dependentBreakpointManager.getSlaveBreakpoints(breakpoint);
breakpoints.forEach(myInactiveSlaveBreakpoints::remove);
for (XBreakpoint<?> slaveBreakpoint : breakpoints) {
processAllHandlers(slaveBreakpoint, true);
}
if (dependentBreakpointManager.getMasterBreakpoint(breakpoint) != null && !dependentBreakpointManager.isLeaveEnabled(breakpoint)) {
boolean added = myInactiveSlaveBreakpoints.add(breakpoint);
if (added) {
processAllHandlers(breakpoint, false);
myDebuggerManager.getBreakpointManager().getLineBreakpointManager().queueBreakpointUpdate(breakpoint);
}
}
}
private void printMessage(final String message, final String hyperLinkText, @Nullable final HyperlinkInfo info) {
AppUIUtil.invokeOnEdt(() -> {
myConsoleView.print(message, ConsoleViewContentType.SYSTEM_OUTPUT);
if (info != null) {
myConsoleView.printHyperlink(hyperLinkText, info);
}
else if (hyperLinkText != null) {
myConsoleView.print(hyperLinkText, ConsoleViewContentType.SYSTEM_OUTPUT);
}
myConsoleView.print("\n", ConsoleViewContentType.SYSTEM_OUTPUT);
});
}
public void unsetPaused() {
myPaused.set(false);
}
private void positionReachedInternal(@NotNull final XSuspendContext suspendContext, boolean attract) {
setBreakpointsDisabledTemporarily(false);
mySuspendContext = suspendContext;
myCurrentExecutionStack = suspendContext.getActiveExecutionStack();
myCurrentStackFrame = myCurrentExecutionStack != null ? myCurrentExecutionStack.getTopFrame() : null;
myIsTopFrame = true;
myTopStackFrame = myCurrentStackFrame;
XSourcePosition topFramePosition = getTopFramePosition();
myPaused.set(true);
boolean isAlternative = myAlternativeSourceHandler != null &&
myAlternativeSourceHandler.isAlternativeSourceKindPreferred(suspendContext);
updateExecutionPosition(isAlternative ? XSourceKind.ALTERNATIVE : XSourceKind.MAIN);
logPositionReached(topFramePosition);
final boolean showOnSuspend = myShowTabOnSuspend.compareAndSet(true, false);
if (showOnSuspend || attract) {
AppUIUtil.invokeLaterIfProjectAlive(myProject, () -> {
if (showOnSuspend) {
initSessionTab(null);
showSessionTab();
}
// user attractions should only be made if event happens independently (e.g. program paused/suspended)
// and should not be made when user steps in the code
if (attract) {
if (mySessionTab == null) {
LOG.debug("Cannot request focus because Session Tab is not initialized yet");
return;
}
if (XDebuggerSettingManagerImpl.getInstanceImpl().getGeneralSettings().isShowDebuggerOnBreakpoint()) {
mySessionTab.toFront(true, this::updateExecutionPosition);
}
if (topFramePosition == null) {
// if there is no source position available, we should somehow tell the user that session is stopped.
// the best way is to show the stack frames.
XDebugSessionTab.showFramesView(this);
}
mySessionTab.getUi().attractBy(XDebuggerUIConstants.LAYOUT_VIEW_BREAKPOINT_CONDITION);
}
});
}
myDispatcher.getMulticaster().sessionPaused();
}
@Override
public void positionReached(@NotNull final XSuspendContext suspendContext) {
positionReached(suspendContext, false);
}
public void positionReached(@NotNull XSuspendContext suspendContext, boolean attract) {
clearActiveNonLineBreakpoint();
positionReachedInternal(suspendContext, attract);
}
@Override
public void sessionResumed() {
doResume();
}
@Override
public boolean isStopped() {
return myStopped.get();
}
private void stopImpl() {
if (!myStopped.compareAndSet(false, true)) {
return;
}
try {
removeBreakpointListeners();
}
finally {
myDebugProcess.stopAsync()
.onSuccess(aVoid -> {
processStopped();
});
}
}
private void processStopped() {
if (!myProject.isDisposed()) {
myProject.getMessageBus().syncPublisher(XDebuggerManager.TOPIC).processStopped(myDebugProcess);
}
if (mySessionTab != null) {
AppUIUtil.invokeOnEdt(() -> {
mySessionTab.getUi().attractBy(XDebuggerUIConstants.LAYOUT_VIEW_FINISH_CONDITION);
((XWatchesViewImpl)mySessionTab.getWatchesView()).updateSessionData();
mySessionTab.detachFromSession();
});
}
else if (myConsoleView != null) {
AppUIUtil.invokeOnEdt(() -> Disposer.dispose(myConsoleView));
}
clearPausedData();
if (myValueMarkers != null) {
myValueMarkers.clear();
}
if (XDebuggerSettingManagerImpl.getInstanceImpl().getGeneralSettings().isUnmuteOnStop()) {
mySessionData.setBreakpointsMuted(false);
}
myDebuggerManager.removeSession(this);
myDispatcher.getMulticaster().sessionStopped();
myDispatcher.getListeners().clear();
myProject.putUserData(InlineDebugRenderer.LinePainter.CACHE, null);
synchronized (myRegisteredBreakpoints) {
myRegisteredBreakpoints.clear();
}
}
private void removeBreakpointListeners() {
Disposable breakpointListenerDisposable = myBreakpointListenerDisposable;
if (breakpointListenerDisposable != null) {
myBreakpointListenerDisposable = null;
Disposer.dispose(breakpointListenerDisposable);
}
}
public boolean isInactiveSlaveBreakpoint(final XBreakpoint<?> breakpoint) {
return myInactiveSlaveBreakpoints.contains(breakpoint);
}
@Override
public void stop() {
ProcessHandler processHandler = myDebugProcess == null ? null : myDebugProcess.getProcessHandler();
if (processHandler == null || processHandler.isProcessTerminated() || processHandler.isProcessTerminating()) return;
if (processHandler.detachIsDefault()) {
processHandler.detachProcess();
}
else {
processHandler.destroyProcess();
}
}
@Override
public void reportError(@NotNull final String message) {
reportMessage(message, MessageType.ERROR);
}
@Override
public void reportMessage(@NotNull final String message, @NotNull final MessageType type) {
reportMessage(message, type, null);
}
@Override
public void reportMessage(@NotNull final String message, @NotNull final MessageType type, @Nullable final HyperlinkListener listener) {
Notification notification = XDebuggerManagerImpl.getNotificationGroup().createNotification(message, type.toNotificationType());
if (listener != null) {
notification.setListener((__, event) -> {
if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
listener.hyperlinkUpdate(event);
}
});
}
notification.notify(myProject);
}
private final class MyBreakpointListener implements XBreakpointListener<XBreakpoint<?>> {
@Override
public void breakpointAdded(@NotNull final XBreakpoint<?> breakpoint) {
if (processAdd(breakpoint)) {
CustomizedBreakpointPresentation presentation = getBreakpointPresentation(breakpoint);
if (presentation != null) {
if (XDebuggerUtilImpl.getVerifiedIcon(breakpoint).equals(presentation.getIcon())) {
BreakpointsUsageCollector.reportBreakpointVerified(breakpoint, 0);
}
else {
presentation.setTimestamp(System.currentTimeMillis());
}
}
}
}
@Override
public void breakpointRemoved(@NotNull final XBreakpoint<?> breakpoint) {
checkActiveNonLineBreakpointOnRemoval(breakpoint);
processRemove(breakpoint);
}
void processRemove(@NotNull final XBreakpoint<?> breakpoint) {
processAllHandlers(breakpoint, false);
}
boolean processAdd(@NotNull final XBreakpoint<?> breakpoint) {
if (!myBreakpointsDisabled) {
processAllHandlers(breakpoint, true);
return true;
}
return false;
}
@Override
public void breakpointChanged(@NotNull final XBreakpoint<?> breakpoint) {
processRemove(breakpoint);
processAdd(breakpoint);
}
}
private class MyDependentBreakpointListener implements XDependentBreakpointListener {
@Override
public void dependencySet(@NotNull final XBreakpoint<?> slave, @NotNull final XBreakpoint<?> master) {
boolean added = myInactiveSlaveBreakpoints.add(slave);
if (added) {
processAllHandlers(slave, false);
}
}
@Override
public void dependencyCleared(final XBreakpoint<?> breakpoint) {
boolean removed = myInactiveSlaveBreakpoints.remove(breakpoint);
if (removed) {
processAllHandlers(breakpoint, true);
}
}
}
private @NotNull String computeConfigurationName() {
if (myEnvironment != null) {
RunProfile profile = myEnvironment.getRunProfile();
if (profile instanceof RunConfiguration) {
return ((RunConfiguration)profile).getType().getId();
}
}
return getSessionName();
}
@Nullable
public ExecutionEnvironment getExecutionEnvironment() {
return myEnvironment;
}
private void rememberUserActionStart(@NotNull String action) {
myUserRequestStart = System.currentTimeMillis();
myUserRequestAction = action;
}
private void logPositionReached(@Nullable XSourcePosition topFramePosition) {
FileType fileType = topFramePosition != null ? topFramePosition.getFile().getFileType() : null;
if (myUserRequestAction != null) {
long durationMs = System.currentTimeMillis() - myUserRequestStart;
if (PERFORMANCE_LOG.isDebugEnabled()) {
PERFORMANCE_LOG.debug("Position reached in " + durationMs + "ms");
}
XDebuggerPerformanceCollector.logExecutionPointReached(myProject, fileType, myUserRequestAction, durationMs);
myUserRequestAction = null;
}
else {
XDebuggerPerformanceCollector.logBreakpointReached(myProject, fileType);
}
}
}
| JetBrains/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebugSessionImpl.java |
45,346 | //CHECKSTYLE:FileLength:OFF
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2023 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.ui.spoon.trans;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.window.DefaultToolTip;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Widget;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.EngineMetaInterface;
import org.pentaho.di.core.NotePadMeta;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.SwtUniversalImage;
import org.pentaho.di.core.dnd.DragAndDropContainer;
import org.pentaho.di.core.dnd.XMLTransfer;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.extension.ExtensionPointHandler;
import org.pentaho.di.core.extension.KettleExtensionPoint;
import org.pentaho.di.core.gui.AreaOwner;
import org.pentaho.di.core.gui.AreaOwner.AreaType;
import org.pentaho.di.core.gui.BasePainter;
import org.pentaho.di.core.gui.GCInterface;
import org.pentaho.di.core.gui.Point;
import org.pentaho.di.core.gui.Redrawable;
import org.pentaho.di.core.gui.SnapAllignDistribute;
import org.pentaho.di.core.logging.DefaultLogLevel;
import org.pentaho.di.core.logging.HasLogChannelInterface;
import org.pentaho.di.core.logging.KettleLogStore;
import org.pentaho.di.core.logging.KettleLoggingEvent;
import org.pentaho.di.core.logging.LogChannel;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.LogMessage;
import org.pentaho.di.core.logging.LogParentProvidedInterface;
import org.pentaho.di.core.logging.LoggingObjectInterface;
import org.pentaho.di.core.logging.LoggingObjectType;
import org.pentaho.di.core.logging.LoggingRegistry;
import org.pentaho.di.core.logging.SimpleLoggingObject;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.StepPluginType;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.lineage.TransDataLineage;
import org.pentaho.di.repository.KettleRepositoryLostException;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryObjectType;
import org.pentaho.di.repository.RepositoryOperation;
import org.pentaho.di.shared.SharedObjects;
import org.pentaho.di.trans.DatabaseImpact;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransExecutionConfiguration;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransPainter;
import org.pentaho.di.trans.debug.BreakPointListener;
import org.pentaho.di.trans.debug.StepDebugMeta;
import org.pentaho.di.trans.debug.TransDebugMeta;
import org.pentaho.di.trans.debug.TransDebugMetaWrapper;
import org.pentaho.di.trans.step.RemoteStep;
import org.pentaho.di.trans.step.RowDistributionInterface;
import org.pentaho.di.trans.step.RowDistributionPluginType;
import org.pentaho.di.trans.step.RowListener;
import org.pentaho.di.trans.step.StepErrorMeta;
import org.pentaho.di.trans.step.StepIOMetaInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaDataCombi;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.step.errorhandling.Stream;
import org.pentaho.di.trans.step.errorhandling.StreamIcon;
import org.pentaho.di.trans.step.errorhandling.StreamInterface;
import org.pentaho.di.trans.step.errorhandling.StreamInterface.StreamType;
import org.pentaho.di.trans.steps.tableinput.TableInputMeta;
import org.pentaho.di.ui.core.ConstUI;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.dialog.DialogClosedListener;
import org.pentaho.di.ui.core.dialog.EnterSelectionDialog;
import org.pentaho.di.ui.core.dialog.EnterStringDialog;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.dialog.StepFieldsDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.widget.CheckBoxToolTip;
import org.pentaho.di.ui.core.widget.CheckBoxToolTipListener;
import org.pentaho.di.ui.repository.RepositorySecurityUI;
import org.pentaho.di.ui.repository.dialog.RepositoryExplorerDialog;
import org.pentaho.di.ui.repository.dialog.RepositoryRevisionBrowserDialogInterface;
import org.pentaho.di.ui.spoon.AbstractGraph;
import org.pentaho.di.ui.spoon.SWTGC;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.spoon.SpoonPluginManager;
import org.pentaho.di.ui.spoon.SpoonUiExtenderPluginInterface;
import org.pentaho.di.ui.spoon.SpoonUiExtenderPluginType;
import org.pentaho.di.ui.spoon.SwtScrollBar;
import org.pentaho.di.ui.spoon.TabItemInterface;
import org.pentaho.di.ui.spoon.XulSpoonResourceBundle;
import org.pentaho.di.ui.spoon.XulSpoonSettingsManager;
import org.pentaho.di.ui.spoon.dialog.EnterPreviewRowsDialog;
import org.pentaho.di.ui.spoon.dialog.NotePadDialog;
import org.pentaho.di.ui.spoon.dialog.SearchFieldsProgressDialog;
import org.pentaho.di.ui.spoon.job.JobGraph;
import org.pentaho.di.ui.trans.dialog.TransDialog;
import org.pentaho.di.ui.xul.KettleXulLoader;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.components.XulMenuitem;
import org.pentaho.ui.xul.components.XulToolbarbutton;
import org.pentaho.ui.xul.containers.XulMenu;
import org.pentaho.ui.xul.containers.XulMenupopup;
import org.pentaho.ui.xul.containers.XulToolbar;
import org.pentaho.ui.xul.dom.Document;
import org.pentaho.ui.xul.impl.XulEventHandler;
import org.pentaho.ui.xul.jface.tags.JfaceMenuitem;
import org.pentaho.ui.xul.jface.tags.JfaceMenupopup;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Callable;
/**
* This class handles the display of the transformations in a graphical way using icons, arrows, etc. One transformation
* is handled per TransGraph
*
* @author Matt
* @since 17-mei-2003
*/
public class TransGraph extends AbstractGraph implements XulEventHandler, Redrawable, TabItemInterface,
LogParentProvidedInterface, MouseListener, MouseMoveListener, MouseTrackListener, MouseWheelListener, KeyListener {
private static Class<?> PKG = Spoon.class; // for i18n purposes, needed by Translator2!!
private LogChannelInterface log;
private static final int HOP_SEL_MARGIN = 9;
private static final String XUL_FILE_TRANS_TOOLBAR = "ui/trans-toolbar.xul";
public static final String LOAD_TAB = "loadTab";
public static final String PREVIEW_TRANS = "previewTrans";
public static final String START_TEXT = BaseMessages.getString( PKG, "TransLog.Button.StartTransformation" );
public static final String PAUSE_TEXT = BaseMessages.getString( PKG, "TransLog.Button.PauseTransformation" );
public static final String RESUME_TEXT = BaseMessages.getString( PKG, "TransLog.Button.ResumeTransformation" );
public static final String STOP_TEXT = BaseMessages.getString( PKG, "TransLog.Button.StopTransformation" );
public static final String TRANS_GRAPH_ENTRY_SNIFF = "trans-graph-entry-sniff";
public static final String TRANS_GRAPH_ENTRY_AGAIN = "trans-graph-entry-align";
private static final int TOOLTIP_HIDE_DELAY_SHORT = 5000;
private static final int TOOLTIP_HIDE_DELAY_LONG = 10000;
private TransMeta transMeta;
public Trans trans;
private Shell shell;
private Composite mainComposite;
private DefaultToolTip toolTip;
private CheckBoxToolTip helpTip;
private XulToolbar toolbar;
private int iconsize;
private Point lastclick;
private Point lastMove;
private Point[] previous_step_locations;
private Point[] previous_note_locations;
private List<StepMeta> selectedSteps;
private StepMeta selectedStep;
private List<StepMeta> mouseOverSteps;
private List<NotePadMeta> selectedNotes;
private NotePadMeta selectedNote;
private TransHopMeta candidate;
private Point drop_candidate;
private Spoon spoon;
// public boolean shift, control;
private boolean split_hop;
private int lastButton;
private TransHopMeta last_hop_split;
private org.pentaho.di.core.gui.Rectangle selectionRegion;
/**
* A list of remarks on the current Transformation...
*/
private List<CheckResultInterface> remarks;
/**
* A list of impacts of the current transformation on the used databases.
*/
private List<DatabaseImpact> impact;
/**
* Indicates whether or not an impact analysis has already run.
*/
private boolean impactFinished;
private TransDebugMeta lastTransDebugMeta;
private Map<String, XulMenupopup> menuMap = new HashMap<>();
protected int currentMouseX = 0;
protected int currentMouseY = 0;
protected NotePadMeta ni = null;
protected TransHopMeta currentHop;
protected StepMeta currentStep;
private List<AreaOwner> areaOwners;
// private Text filenameLabel;
private SashForm sashForm;
public Composite extraViewComposite;
public CTabFolder extraViewTabFolder;
private boolean initialized;
private boolean running;
private boolean halted;
private boolean halting;
private boolean safeStopping;
private boolean debug;
private boolean pausing;
public TransLogDelegate transLogDelegate;
public TransGridDelegate transGridDelegate;
public TransHistoryDelegate transHistoryDelegate;
public TransPerfDelegate transPerfDelegate;
public TransMetricsDelegate transMetricsDelegate;
public TransPreviewDelegate transPreviewDelegate;
public List<SelectedStepListener> stepListeners;
public List<StepSelectionListener> currentStepListeners = new ArrayList<>();
/**
* A map that keeps track of which log line was written by which step
*/
private Map<StepMeta, String> stepLogMap;
private StepMeta startHopStep;
private Point endHopLocation;
private boolean startErrorHopStep;
private StepMeta noInputStep;
private StepMeta endHopStep;
private StreamType candidateHopType;
private Map<StepMeta, DelayTimer> delayTimers;
private StepMeta showTargetStreamsStep;
Timer redrawTimer;
private ToolItem stopItem;
public void setCurrentNote( NotePadMeta ni ) {
this.ni = ni;
}
public NotePadMeta getCurrentNote() {
return ni;
}
public TransHopMeta getCurrentHop() {
return currentHop;
}
public void setCurrentHop( TransHopMeta currentHop ) {
this.currentHop = currentHop;
}
public StepMeta getCurrentStep() {
return currentStep;
}
public void setCurrentStep( StepMeta currentStep ) {
this.currentStep = currentStep;
}
public void addSelectedStepListener( SelectedStepListener selectedStepListener ) {
stepListeners.add( selectedStepListener );
}
public void addCurrentStepListener( StepSelectionListener stepSelectionListener ) {
currentStepListeners.add( stepSelectionListener );
}
public TransGraph( Composite parent, final Spoon spoon, final TransMeta transMeta ) {
super( parent, SWT.NONE );
this.shell = parent.getShell();
this.spoon = spoon;
this.transMeta = transMeta;
this.areaOwners = new ArrayList<>();
this.log = spoon.getLog();
spoon.clearSearchFilter();
this.mouseOverSteps = new ArrayList<>();
this.delayTimers = new HashMap<>();
transLogDelegate = new TransLogDelegate( spoon, this );
transGridDelegate = new TransGridDelegate( spoon, this );
transHistoryDelegate = new TransHistoryDelegate( spoon, this );
transPerfDelegate = new TransPerfDelegate( spoon, this );
transMetricsDelegate = new TransMetricsDelegate( spoon, this );
transPreviewDelegate = new TransPreviewDelegate( spoon, this );
stepListeners = new ArrayList<>();
try {
KettleXulLoader loader = new KettleXulLoader();
loader.setIconsSize( 16, 16 );
loader.setSettingsManager( XulSpoonSettingsManager.getInstance() );
ResourceBundle bundle = new XulSpoonResourceBundle( Spoon.class );
XulDomContainer container = loader.loadXul( XUL_FILE_TRANS_TOOLBAR, bundle );
container.addEventHandler( this );
SpoonPluginManager.getInstance().applyPluginsForContainer( "trans-graph", xulDomContainer );
setXulDomContainer( container );
} catch ( XulException e1 ) {
log.logError( "Error loading XUL resource bundle for Spoon", e1 );
}
setLayout( new FormLayout() );
setLayoutData( new GridData( GridData.FILL_BOTH ) );
// Add a tool-bar at the top of the tab
// The form-data is set on the native widget automatically
//
addToolBar();
setControlStates(); // enable / disable the icons in the toolbar too.
// The main composite contains the graph view, but if needed also
// a view with an extra tab containing log, etc.
//
mainComposite = new Composite( this, SWT.NONE );
mainComposite.setLayout( new FillLayout() );
// Nick's fix below -------
Control toolbarControl = (Control) toolbar.getManagedObject();
FormData toolbarFd = new FormData();
toolbarFd.left = new FormAttachment( 0, 0 );
toolbarFd.right = new FormAttachment( 100, 0 );
toolbarControl.setLayoutData( toolbarFd );
toolbarControl.setParent( this );
// ------------------------
FormData fdMainComposite = new FormData();
fdMainComposite.left = new FormAttachment( 0, 0 );
fdMainComposite.top = new FormAttachment( (Control) toolbar.getManagedObject(), 0 );
fdMainComposite.right = new FormAttachment( 100, 0 );
fdMainComposite.bottom = new FormAttachment( 100, 0 );
mainComposite.setLayoutData( fdMainComposite );
// To allow for a splitter later on, we will add the splitter here...
//
sashForm = new SashForm( mainComposite, SWT.VERTICAL );
// Add a canvas below it, use up all space initially
//
canvas = new Canvas( sashForm, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_BACKGROUND | SWT.BORDER );
sashForm.setWeights( new int[] { 100, } );
try {
// first get the XML document
menuMap.put( "trans-graph-hop", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById(
"trans-graph-hop" ) );
menuMap.put( "trans-graph-entry", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById(
"trans-graph-entry" ) );
menuMap.put( "trans-graph-background", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById(
"trans-graph-background" ) );
menuMap.put( "trans-graph-note", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById(
"trans-graph-note" ) );
} catch ( Throwable t ) {
log.logError( "Error parsing XUL XML", t );
}
toolTip = new DefaultToolTip( canvas, ToolTip.NO_RECREATE, true );
toolTip.setRespectMonitorBounds( true );
toolTip.setRespectDisplayBounds( true );
toolTip.setPopupDelay( 350 );
toolTip.setHideDelay( TOOLTIP_HIDE_DELAY_SHORT );
toolTip.setShift( new org.eclipse.swt.graphics.Point( ConstUI.TOOLTIP_OFFSET, ConstUI.TOOLTIP_OFFSET ) );
helpTip = new CheckBoxToolTip( canvas );
helpTip.addCheckBoxToolTipListener( new CheckBoxToolTipListener() {
@Override
public void checkBoxSelected( boolean enabled ) {
spoon.props.setShowingHelpToolTips( enabled );
}
} );
iconsize = spoon.props.getIconSize();
clearSettings();
remarks = new ArrayList<>();
impact = new ArrayList<>();
impactFinished = false;
hori = canvas.getHorizontalBar();
vert = canvas.getVerticalBar();
hori.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e ) {
redraw();
}
} );
vert.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e ) {
redraw();
}
} );
hori.setThumb( 100 );
vert.setThumb( 100 );
hori.setVisible( true );
vert.setVisible( true );
setVisible( true );
newProps();
canvas.setBackground( GUIResource.getInstance().getColorBackground() );
canvas.addPaintListener( new PaintListener() {
@Override
public void paintControl( PaintEvent e ) {
if ( !spoon.isStopped() ) {
TransGraph.this.paintControl( e );
}
}
} );
selectedSteps = null;
lastclick = null;
/*
* Handle the mouse...
*/
canvas.addMouseListener( this );
canvas.addMouseMoveListener( this );
canvas.addMouseTrackListener( this );
canvas.addMouseWheelListener( this );
canvas.addKeyListener( this );
// Drag & Drop for steps
Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() };
DropTarget ddTarget = new DropTarget( canvas, DND.DROP_MOVE );
ddTarget.setTransfer( ttypes );
ddTarget.addDropListener( new DropTargetListener() {
@Override
public void dragEnter( DropTargetEvent event ) {
clearSettings();
drop_candidate = PropsUI.calculateGridPosition( getRealPosition( canvas, event.x, event.y ) );
redraw();
}
@Override
public void dragLeave( DropTargetEvent event ) {
drop_candidate = null;
redraw();
}
@Override
public void dragOperationChanged( DropTargetEvent event ) {
}
@Override
public void dragOver( DropTargetEvent event ) {
drop_candidate = PropsUI.calculateGridPosition( getRealPosition( canvas, event.x, event.y ) );
redraw();
}
@Override
public void drop( DropTargetEvent event ) {
// no data to copy, indicate failure in event.detail
if ( event.data == null ) {
event.detail = DND.DROP_NONE;
return;
}
// System.out.println("Dropping a step!!");
// What's the real drop position?
Point p = getRealPosition( canvas, event.x, event.y );
//
// We expect a Drag and Drop container... (encased in XML)
try {
DragAndDropContainer container = (DragAndDropContainer) event.data;
StepMeta stepMeta = null;
boolean newstep = false;
switch ( container.getType() ) {
// Put an existing one on the canvas.
case DragAndDropContainer.TYPE_STEP:
// Drop hidden step onto canvas....
stepMeta = transMeta.findStep( container.getData() );
if ( stepMeta != null ) {
if ( stepMeta.isDrawn() || transMeta.isStepUsedInTransHops( stepMeta ) ) {
modalMessageDialog( getString( "TransGraph.Dialog.StepIsAlreadyOnCanvas.Title" ),
getString( "TransGraph.Dialog.StepIsAlreadyOnCanvas.Message" ), SWT.OK );
return;
}
// This step gets the drawn attribute and position set below.
} else {
// Unknown step dropped: ignore this to be safe!
return;
}
break;
// Create a new step
case DragAndDropContainer.TYPE_BASE_STEP_TYPE:
// Not an existing step: data refers to the type of step to create
String id = container.getId();
String name = container.getData();
stepMeta = spoon.newStep( transMeta, id, name, name, false, true );
if ( stepMeta != null ) {
newstep = true;
} else {
return; // Cancelled pressed in dialog or unable to create step.
}
break;
// Create a new TableInput step using the selected connection...
case DragAndDropContainer.TYPE_DATABASE_CONNECTION:
newstep = true;
String connectionName = container.getData();
TableInputMeta tii = new TableInputMeta();
tii.setDatabaseMeta( transMeta.findDatabase( connectionName ) );
PluginRegistry registry = PluginRegistry.getInstance();
String stepID = registry.getPluginId( StepPluginType.class, tii );
PluginInterface stepPlugin = registry.findPluginWithId( StepPluginType.class, stepID );
String stepName = transMeta.getAlternativeStepname( stepPlugin.getName() );
stepMeta = new StepMeta( stepID, stepName, tii );
if ( spoon.editStep( transMeta, stepMeta ) != null ) {
transMeta.addStep( stepMeta );
spoon.refreshTree();
spoon.refreshGraph();
} else {
return;
}
break;
// Drag hop on the canvas: create a new Hop...
case DragAndDropContainer.TYPE_TRANS_HOP:
newHop();
return;
default:
// Nothing we can use: give an error!
modalMessageDialog( getString( "TransGraph.Dialog.ItemCanNotBePlacedOnCanvas.Title" ),
getString( "TransGraph.Dialog.ItemCanNotBePlacedOnCanvas.Message" ), SWT.OK );
return;
}
transMeta.unselectAll();
StepMeta before = null;
if ( !newstep ) {
before = (StepMeta) stepMeta.clone();
}
stepMeta.drawStep();
stepMeta.setSelected( true );
PropsUI.setLocation( stepMeta, p.x, p.y );
if ( newstep ) {
spoon.addUndoNew( transMeta, new StepMeta[] { stepMeta }, new int[] { transMeta.indexOfStep( stepMeta ) } );
} else {
spoon.addUndoChange( transMeta, new StepMeta[] { before }, new StepMeta[] { (StepMeta) stepMeta.clone() },
new int[] { transMeta.indexOfStep( stepMeta ) } );
}
canvas.forceFocus();
redraw();
// See if we want to draw a tool tip explaining how to create new hops...
//
if ( newstep && transMeta.nrSteps() > 1 && transMeta.nrSteps() < 5 && spoon.props.isShowingHelpToolTips() ) {
showHelpTip( p.x, p.y, BaseMessages.getString( PKG, "TransGraph.HelpToolTip.CreatingHops.Title" ),
BaseMessages.getString( PKG, "TransGraph.HelpToolTip.CreatingHops.Message" ) );
}
} catch ( Exception e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "TransGraph.Dialog.ErrorDroppingObject.Message" ),
BaseMessages.getString( PKG, "TransGraph.Dialog.ErrorDroppingObject.Title" ), e );
}
}
@Override
public void dropAccept( DropTargetEvent event ) {
}
} );
setBackground( GUIResource.getInstance().getColorBackground() );
// Add a timer to set correct the state of the run/stop buttons every 2 seconds...
//
final Timer timer = new Timer( "TransGraph.setControlStates Timer: " + getMeta().getName() );
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
try {
setControlStates();
} catch ( KettleRepositoryLostException krle ) {
if ( log.isBasic() ) {
log.logBasic( krle.getLocalizedMessage() );
}
}
}
};
timer.schedule( timerTask, 2000, 1000 );
// Make sure the timer stops when we close the tab...
//
addDisposeListener( new DisposeListener() {
@Override
public void widgetDisposed( DisposeEvent arg0 ) {
timer.cancel();
}
} );
}
@Override
public void mouseDoubleClick( MouseEvent e ) {
clearSettings();
Point real = screen2real( e.x, e.y );
// Hide the tooltip!
hideToolTips();
try {
ExtensionPointHandler.callExtensionPoint( LogChannel.GENERAL, KettleExtensionPoint.TransGraphMouseDoubleClick.id,
new TransGraphExtension( this, e, real ) );
} catch ( Exception ex ) {
LogChannel.GENERAL.logError( "Error calling TransGraphMouseDoubleClick extension point", ex );
}
StepMeta stepMeta = transMeta.getStep( real.x, real.y, iconsize );
if ( stepMeta != null ) {
if ( e.button == 1 ) {
editStep( stepMeta );
} else {
editDescription( stepMeta );
}
} else {
// Check if point lies on one of the many hop-lines...
TransHopMeta online = findHop( real.x, real.y );
if ( online != null ) {
editHop( online );
} else {
NotePadMeta ni = transMeta.getNote( real.x, real.y );
if ( ni != null ) {
selectedNote = null;
editNote( ni );
} else {
// See if the double click was in one of the area's...
//
boolean hit = false;
for ( AreaOwner areaOwner : areaOwners ) {
if ( areaOwner.contains( real.x, real.y ) ) {
if ( areaOwner.getParent() instanceof StepMeta
&& areaOwner.getOwner().equals( TransPainter.STRING_PARTITIONING_CURRENT_STEP ) ) {
StepMeta step = (StepMeta) areaOwner.getParent();
spoon.editPartitioning( transMeta, step );
hit = true;
break;
}
}
}
if ( !hit ) {
settings();
}
}
}
}
}
@Override
public void mouseDown( MouseEvent e ) {
boolean alt = ( e.stateMask & SWT.ALT ) != 0;
boolean control = ( e.stateMask & SWT.MOD1 ) != 0;
boolean shift = ( e.stateMask & SWT.SHIFT ) != 0;
lastButton = e.button;
Point real = screen2real( e.x, e.y );
lastclick = new Point( real.x, real.y );
// Hide the tooltip!
hideToolTips();
// Set the pop-up menu
if ( e.button == 3 ) {
setMenu( real.x, real.y );
return;
}
try {
ExtensionPointHandler.callExtensionPoint( LogChannel.GENERAL, KettleExtensionPoint.TransGraphMouseDown.id,
new TransGraphExtension( this, e, real ) );
} catch ( Exception ex ) {
LogChannel.GENERAL.logError( "Error calling TransGraphMouseDown extension point", ex );
}
// A single left or middle click on one of the area owners...
//
if ( e.button == 1 || e.button == 2 ) {
AreaOwner areaOwner = getVisibleAreaOwner( real.x, real.y );
if ( areaOwner != null && areaOwner.getAreaType() != null ) {
switch ( areaOwner.getAreaType() ) {
case STEP_OUTPUT_HOP_ICON:
// Click on the output icon means: start of drag
// Action: We show the input icons on the other steps...
//
selectedStep = null;
startHopStep = (StepMeta) areaOwner.getParent();
candidateHopType = null;
startErrorHopStep = false;
// stopStepMouseOverDelayTimer(startHopStep);
break;
case STEP_INPUT_HOP_ICON:
// Click on the input icon means: start to a new hop
// In this case, we set the end hop step...
//
selectedStep = null;
startHopStep = null;
endHopStep = (StepMeta) areaOwner.getParent();
candidateHopType = null;
startErrorHopStep = false;
// stopStepMouseOverDelayTimer(endHopStep);
break;
case HOP_ERROR_ICON:
// Click on the error icon means: Edit error handling
//
StepMeta stepMeta = (StepMeta) areaOwner.getParent();
spoon.editStepErrorHandling( transMeta, stepMeta );
break;
case STEP_TARGET_HOP_ICON_OPTION:
// Below, see showStepTargetOptions()
break;
case STEP_EDIT_ICON:
clearSettings();
currentStep = (StepMeta) areaOwner.getParent();
stopStepMouseOverDelayTimer( currentStep );
editStep();
break;
case STEP_INJECT_ICON:
modalMessageDialog( getString( "TransGraph.StepInjectionSupported.Title" ),
getString( "TransGraph.StepInjectionSupported.Tooltip" ), SWT.OK | SWT.ICON_INFORMATION );
break;
case STEP_MENU_ICON:
clearSettings();
stepMeta = (StepMeta) areaOwner.getParent();
setMenu( stepMeta.getLocation().x, stepMeta.getLocation().y );
break;
case STEP_ICON:
stepMeta = (StepMeta) areaOwner.getOwner();
currentStep = stepMeta;
for ( StepSelectionListener listener : currentStepListeners ) {
listener.onUpdateSelection( currentStep );
}
if ( candidate != null ) {
addCandidateAsHop( e.x, e.y );
} else {
if ( transPreviewDelegate.isActive() ) {
transPreviewDelegate.setSelectedStep( currentStep );
for ( SelectedStepListener stepListener : stepListeners ) {
if ( this.extraViewComposite != null && !this.extraViewComposite.isDisposed() ) {
stepListener.onSelect( currentStep );
}
}
transPreviewDelegate.refreshView();
}
}
// ALT-Click: edit error handling
//
if ( e.button == 1 && alt && stepMeta.supportsErrorHandling() ) {
spoon.editStepErrorHandling( transMeta, stepMeta );
return;
} else if ( e.button == 2 || ( e.button == 1 && shift ) ) {
// SHIFT CLICK is start of drag to create a new hop
//
startHopStep = stepMeta;
} else {
selectedSteps = transMeta.getSelectedSteps();
selectedStep = stepMeta;
//
// When an icon is moved that is not selected, it gets
// selected too late.
// It is not captured here, but in the mouseMoveListener...
//
previous_step_locations = transMeta.getSelectedStepLocations();
Point p = stepMeta.getLocation();
iconoffset = new Point( real.x - p.x, real.y - p.y );
}
redraw();
break;
case NOTE:
ni = (NotePadMeta) areaOwner.getOwner();
selectedNotes = transMeta.getSelectedNotes();
selectedNote = ni;
Point loc = ni.getLocation();
previous_note_locations = transMeta.getSelectedNoteLocations();
noteoffset = new Point( real.x - loc.x, real.y - loc.y );
redraw();
break;
case STEP_COPIES_TEXT:
copies( (StepMeta) areaOwner.getOwner() );
break;
case STEP_DATA_SERVICE:
editProperties( transMeta, spoon, spoon.getRepository(), true, TransDialog.Tabs.EXTRA_TAB );
break;
default:
break;
}
} else {
// A hop? --> enable/disable
//
TransHopMeta hop = findHop( real.x, real.y );
if ( hop != null ) {
TransHopMeta before = (TransHopMeta) hop.clone();
setHopEnabled( hop, !hop.isEnabled() );
if ( hop.isEnabled() && transMeta.hasLoop( hop.getToStep() ) ) {
setHopEnabled( hop, false );
modalMessageDialog( getString( "TransGraph.Dialog.HopCausesLoop.Title" ),
getString( "TransGraph.Dialog.HopCausesLoop.Message" ), SWT.OK | SWT.ICON_ERROR );
}
TransHopMeta after = (TransHopMeta) hop.clone();
spoon.addUndoChange( transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after },
new int[] { transMeta.indexOfTransHop( hop ) } );
redraw();
spoon.setShellText();
} else {
// No area-owner & no hop means : background click:
//
startHopStep = null;
if ( !control ) {
selectionRegion = new org.pentaho.di.core.gui.Rectangle( real.x, real.y, 0, 0 );
}
redraw();
}
}
}
}
@Override
public void mouseUp( MouseEvent e ) {
try {
TransGraphExtension ext = new TransGraphExtension( null, e, getArea() );
ExtensionPointHandler.callExtensionPoint( LogChannel.GENERAL, KettleExtensionPoint.TransGraphMouseUp.id, ext );
if ( ext.isPreventDefault() ) {
redraw();
clearSettings();
return;
}
} catch ( Exception ex ) {
LogChannel.GENERAL.logError( "Error calling TransGraphMouseUp extension point", ex );
}
boolean control = ( e.stateMask & SWT.MOD1 ) != 0;
TransHopMeta selectedHop = findHop( e.x, e.y );
updateErrorMetaForHop( selectedHop );
if ( iconoffset == null ) {
iconoffset = new Point( 0, 0 );
}
Point real = screen2real( e.x, e.y );
Point icon = new Point( real.x - iconoffset.x, real.y - iconoffset.y );
AreaOwner areaOwner = getVisibleAreaOwner( real.x, real.y );
try {
TransGraphExtension ext = new TransGraphExtension( this, e, real );
ExtensionPointHandler.callExtensionPoint( LogChannel.GENERAL, KettleExtensionPoint.TransGraphMouseUp.id, ext );
if ( ext.isPreventDefault() ) {
redraw();
clearSettings();
return;
}
} catch ( Exception ex ) {
LogChannel.GENERAL.logError( "Error calling TransGraphMouseUp extension point", ex );
}
// Quick new hop option? (drag from one step to another)
//
if ( candidate != null && areaOwner != null && areaOwner.getAreaType() != null ) {
switch ( areaOwner.getAreaType() ) {
case STEP_ICON:
currentStep = (StepMeta) areaOwner.getOwner();
break;
case STEP_INPUT_HOP_ICON:
currentStep = (StepMeta) areaOwner.getParent();
break;
default:
break;
}
addCandidateAsHop( e.x, e.y );
redraw();
} else {
// Did we select a region on the screen? Mark steps in region as
// selected
//
if ( selectionRegion != null ) {
selectionRegion.width = real.x - selectionRegion.x;
selectionRegion.height = real.y - selectionRegion.y;
transMeta.unselectAll();
selectInRect( transMeta, selectionRegion );
selectionRegion = null;
stopStepMouseOverDelayTimers();
redraw();
} else {
// Clicked on an icon?
//
if ( selectedStep != null && startHopStep == null ) {
if ( e.button == 1 ) {
Point realclick = screen2real( e.x, e.y );
if ( lastclick.x == realclick.x && lastclick.y == realclick.y ) {
// Flip selection when control is pressed!
if ( control ) {
selectedStep.flipSelected();
} else {
// Otherwise, select only the icon clicked on!
transMeta.unselectAll();
selectedStep.setSelected( true );
}
} else {
// Find out which Steps & Notes are selected
selectedSteps = transMeta.getSelectedSteps();
selectedNotes = transMeta.getSelectedNotes();
// We moved around some items: store undo info...
//
boolean also = false;
if ( selectedNotes != null && selectedNotes.size() > 0 && previous_note_locations != null ) {
int[] indexes = transMeta.getNoteIndexes( selectedNotes );
addUndoPosition( selectedNotes.toArray( new NotePadMeta[ selectedNotes.size() ] ), indexes,
previous_note_locations, transMeta.getSelectedNoteLocations(), also );
also = selectedSteps != null && selectedSteps.size() > 0;
}
if ( selectedSteps != null && previous_step_locations != null ) {
int[] indexes = transMeta.getStepIndexes( selectedSteps );
addUndoPosition( selectedSteps.toArray( new StepMeta[ selectedSteps.size() ] ), indexes,
previous_step_locations, transMeta.getSelectedStepLocations(), also );
}
}
}
// OK, we moved the step, did we move it across a hop?
// If so, ask to split the hop!
if ( split_hop ) {
TransHopMeta hi = findHop( icon.x + iconsize / 2, icon.y + iconsize / 2, selectedStep );
if ( hi != null ) {
splitHop( hi );
}
split_hop = false;
}
selectedSteps = null;
selectedNotes = null;
selectedStep = null;
selectedNote = null;
startHopStep = null;
endHopLocation = null;
redraw();
spoon.setShellText();
} else {
// Notes?
//
if ( selectedNote != null ) {
if ( e.button == 1 ) {
if ( lastclick.x == e.x && lastclick.y == e.y ) {
// Flip selection when control is pressed!
if ( control ) {
selectedNote.flipSelected();
} else {
// Otherwise, select only the note clicked on!
transMeta.unselectAll();
selectedNote.setSelected( true );
}
} else {
// Find out which Steps & Notes are selected
selectedSteps = transMeta.getSelectedSteps();
selectedNotes = transMeta.getSelectedNotes();
// We moved around some items: store undo info...
boolean also = false;
if ( selectedNotes != null && selectedNotes.size() > 0 && previous_note_locations != null ) {
int[] indexes = transMeta.getNoteIndexes( selectedNotes );
addUndoPosition( selectedNotes.toArray( new NotePadMeta[ selectedNotes.size() ] ), indexes,
previous_note_locations, transMeta.getSelectedNoteLocations(), also );
also = selectedSteps != null && selectedSteps.size() > 0;
}
if ( selectedSteps != null && selectedSteps.size() > 0 && previous_step_locations != null ) {
int[] indexes = transMeta.getStepIndexes( selectedSteps );
addUndoPosition( selectedSteps.toArray( new StepMeta[ selectedSteps.size() ] ), indexes,
previous_step_locations, transMeta.getSelectedStepLocations(), also );
}
}
}
selectedNotes = null;
selectedSteps = null;
selectedStep = null;
selectedNote = null;
startHopStep = null;
endHopLocation = null;
} else {
if ( areaOwner == null && selectionRegion == null ) {
// Hit absolutely nothing: clear the settings
//
clearSettings();
}
}
}
}
}
lastButton = 0;
}
private void splitHop( TransHopMeta hi ) {
int id = 0;
if ( !spoon.props.getAutoSplit() ) {
MessageDialogWithToggle md =
new MessageDialogWithToggle( shell, BaseMessages.getString( PKG, "TransGraph.Dialog.SplitHop.Title" ), null,
BaseMessages.getString( PKG, "TransGraph.Dialog.SplitHop.Message" ) + Const.CR + hi.toString(),
MessageDialog.QUESTION, new String[] { BaseMessages.getString( PKG, "System.Button.Yes" ),
BaseMessages.getString( PKG, "System.Button.No" ) }, 0, BaseMessages.getString( PKG,
"TransGraph.Dialog.Option.SplitHop.DoNotAskAgain" ), spoon.props.getAutoSplit() );
MessageDialogWithToggle.setDefaultImage( GUIResource.getInstance().getImageSpoon() );
id = md.open();
spoon.props.setAutoSplit( md.getToggleState() );
}
if ( ( id & 0xFF ) == 0 ) { // Means: "Yes" button clicked!
// Only split A-->--B by putting C in between IF...
// C-->--A or B-->--C don't exists...
// A ==> hi.getFromStep()
// B ==> hi.getToStep();
// C ==> selected_step
//
boolean caExists = transMeta.findTransHop( selectedStep, hi.getFromStep() ) != null;
boolean bcExists = transMeta.findTransHop( hi.getToStep(), selectedStep ) != null;
if ( !caExists && !bcExists ) {
StepMeta fromStep = hi.getFromStep();
StepMeta toStep = hi.getToStep();
// In case step A targets B then we now need to target C
//
StepIOMetaInterface fromIo = fromStep.getStepMetaInterface().getStepIOMeta();
for ( StreamInterface stream : fromIo.getTargetStreams() ) {
if ( stream.getStepMeta() != null && stream.getStepMeta().equals( toStep ) ) {
// This target stream was directed to B, now we need to direct it to C
stream.setStepMeta( selectedStep );
fromStep.getStepMetaInterface().handleStreamSelection( stream );
}
}
// In case step B sources from A then we now need to source from C
//
StepIOMetaInterface toIo = toStep.getStepMetaInterface().getStepIOMeta();
for ( StreamInterface stream : toIo.getInfoStreams() ) {
if ( stream.getStepMeta() != null && stream.getStepMeta().equals( fromStep ) ) {
// This info stream was reading from B, now we need to direct it to C
stream.setStepMeta( selectedStep );
toStep.getStepMetaInterface().handleStreamSelection( stream );
}
}
// In case there is error handling on A, we want to make it point to C now
//
StepErrorMeta errorMeta = fromStep.getStepErrorMeta();
if ( fromStep.isDoingErrorHandling() && toStep.equals( errorMeta.getTargetStep() ) ) {
errorMeta.setTargetStep( selectedStep );
}
TransHopMeta newhop1 = new TransHopMeta( hi.getFromStep(), selectedStep );
if ( transMeta.findTransHop( newhop1 ) == null ) {
transMeta.addTransHop( newhop1 );
spoon.addUndoNew( transMeta, new TransHopMeta[] { newhop1, },
new int[] { transMeta.indexOfTransHop( newhop1 ), }, true );
}
TransHopMeta newhop2 = new TransHopMeta( selectedStep, hi.getToStep() );
if ( transMeta.findTransHop( newhop2 ) == null ) {
transMeta.addTransHop( newhop2 );
spoon.addUndoNew( transMeta, new TransHopMeta[] { newhop2 },
new int[] { transMeta.indexOfTransHop( newhop2 ) }, true );
}
int idx = transMeta.indexOfTransHop( hi );
spoon.addUndoDelete( transMeta, new TransHopMeta[] { hi }, new int[] { idx }, true );
transMeta.removeTransHop( idx );
spoon.refreshTree();
}
// else: Silently discard this hop-split attempt.
}
}
@Override
public void mouseMove( MouseEvent e ) {
boolean shift = ( e.stateMask & SWT.SHIFT ) != 0;
noInputStep = null;
// disable the tooltip
//
toolTip.hide();
toolTip.setHideDelay( TOOLTIP_HIDE_DELAY_SHORT );
Point real = screen2real( e.x, e.y );
// Remember the last position of the mouse for paste with keyboard
//
lastMove = real;
if ( iconoffset == null ) {
iconoffset = new Point( 0, 0 );
}
Point icon = new Point( real.x - iconoffset.x, real.y - iconoffset.y );
if ( noteoffset == null ) {
noteoffset = new Point( 0, 0 );
}
Point note = new Point( real.x - noteoffset.x, real.y - noteoffset.y );
// Moved over an area?
//
AreaOwner areaOwner = getVisibleAreaOwner( real.x, real.y );
if ( areaOwner != null && areaOwner.getAreaType() != null ) {
switch ( areaOwner.getAreaType() ) {
case STEP_ICON:
StepMeta stepMeta = (StepMeta) areaOwner.getOwner();
resetDelayTimer( stepMeta );
break;
case MINI_ICONS_BALLOON: // Give the timer a bit more time
stepMeta = (StepMeta) areaOwner.getParent();
resetDelayTimer( stepMeta );
break;
default:
break;
}
}
try {
TransGraphExtension ext = new TransGraphExtension( this, e, real );
ExtensionPointHandler.callExtensionPoint(
LogChannel.GENERAL, KettleExtensionPoint.TransGraphMouseMoved.id, ext );
} catch ( Exception ex ) {
LogChannel.GENERAL.logError( "Error calling TransGraphMouseMoved extension point", ex );
}
//
// First see if the icon we clicked on was selected.
// If the icon was not selected, we should un-select all other
// icons, selected and move only the one icon
//
if ( selectedStep != null && !selectedStep.isSelected() ) {
transMeta.unselectAll();
selectedStep.setSelected( true );
selectedSteps = new ArrayList<>();
selectedSteps.add( selectedStep );
previous_step_locations = new Point[] { selectedStep.getLocation() };
redraw();
} else if ( selectedNote != null && !selectedNote.isSelected() ) {
transMeta.unselectAll();
selectedNote.setSelected( true );
selectedNotes = new ArrayList<>();
selectedNotes.add( selectedNote );
previous_note_locations = new Point[] { selectedNote.getLocation() };
redraw();
} else if ( selectionRegion != null && startHopStep == null ) {
// Did we select a region...?
//
selectionRegion.width = real.x - selectionRegion.x;
selectionRegion.height = real.y - selectionRegion.y;
redraw();
} else if ( selectedStep != null && lastButton == 1 && !shift && startHopStep == null ) {
//
// One or more icons are selected and moved around...
//
// new : new position of the ICON (not the mouse pointer) dx : difference with previous position
//
int dx = icon.x - selectedStep.getLocation().x;
int dy = icon.y - selectedStep.getLocation().y;
// See if we have a hop-split candidate
//
TransHopMeta hi = findHop( icon.x + iconsize / 2, icon.y + iconsize / 2, selectedStep );
if ( hi != null ) {
// OK, we want to split the hop in 2
//
if ( !hi.getFromStep().equals( selectedStep ) && !hi.getToStep().equals( selectedStep ) ) {
split_hop = true;
last_hop_split = hi;
hi.split = true;
}
} else {
if ( last_hop_split != null ) {
last_hop_split.split = false;
last_hop_split = null;
split_hop = false;
}
}
selectedNotes = transMeta.getSelectedNotes();
selectedSteps = transMeta.getSelectedSteps();
// Adjust location of selected steps...
if ( selectedSteps != null ) {
for ( int i = 0; i < selectedSteps.size(); i++ ) {
StepMeta stepMeta = selectedSteps.get( i );
PropsUI.setLocation( stepMeta, stepMeta.getLocation().x + dx, stepMeta.getLocation().y + dy );
stopStepMouseOverDelayTimer( stepMeta );
}
}
// Adjust location of selected hops...
if ( selectedNotes != null ) {
for ( int i = 0; i < selectedNotes.size(); i++ ) {
NotePadMeta ni = selectedNotes.get( i );
PropsUI.setLocation( ni, ni.getLocation().x + dx, ni.getLocation().y + dy );
}
}
redraw();
} else if ( ( startHopStep != null && endHopStep == null ) || ( endHopStep != null && startHopStep == null ) ) {
// Are we creating a new hop with the middle button or pressing SHIFT?
//
StepMeta stepMeta = transMeta.getStep( real.x, real.y, iconsize );
endHopLocation = new Point( real.x, real.y );
if ( stepMeta != null
&& ( ( startHopStep != null && !startHopStep.equals( stepMeta ) ) || ( endHopStep != null && !endHopStep
.equals( stepMeta ) ) ) ) {
StepIOMetaInterface ioMeta = stepMeta.getStepMetaInterface().getStepIOMeta();
if ( candidate == null ) {
// See if the step accepts input. If not, we can't create a new hop...
//
if ( startHopStep != null ) {
if ( ioMeta.isInputAcceptor() ) {
candidate = new TransHopMeta( startHopStep, stepMeta );
endHopLocation = null;
} else {
noInputStep = stepMeta;
toolTip.setImage( null );
toolTip.setText( "This step does not accept any input from other steps" );
toolTip.show( new org.eclipse.swt.graphics.Point( real.x, real.y ) );
}
} else if ( endHopStep != null ) {
if ( ioMeta.isOutputProducer() ) {
candidate = new TransHopMeta( stepMeta, endHopStep );
endHopLocation = null;
} else {
noInputStep = stepMeta;
toolTip.setImage( null );
toolTip
.setText( "This step doesn't pass any output to other steps. (except perhaps for targetted output)" );
toolTip.show( new org.eclipse.swt.graphics.Point( real.x, real.y ) );
}
}
}
} else {
if ( candidate != null ) {
candidate = null;
redraw();
}
}
redraw();
}
// Move around notes & steps
//
if ( selectedNote != null ) {
if ( lastButton == 1 && !shift ) {
/*
* One or more notes are selected and moved around...
*
* new : new position of the note (not the mouse pointer) dx : difference with previous position
*/
int dx = note.x - selectedNote.getLocation().x;
int dy = note.y - selectedNote.getLocation().y;
selectedNotes = transMeta.getSelectedNotes();
selectedSteps = transMeta.getSelectedSteps();
// Adjust location of selected steps...
if ( selectedSteps != null ) {
for ( int i = 0; i < selectedSteps.size(); i++ ) {
StepMeta stepMeta = selectedSteps.get( i );
PropsUI.setLocation( stepMeta, stepMeta.getLocation().x + dx, stepMeta.getLocation().y + dy );
}
}
// Adjust location of selected hops...
if ( selectedNotes != null ) {
for ( int i = 0; i < selectedNotes.size(); i++ ) {
NotePadMeta ni = selectedNotes.get( i );
PropsUI.setLocation( ni, ni.getLocation().x + dx, ni.getLocation().y + dy );
}
}
redraw();
}
}
}
@Override
public void mouseHover( MouseEvent e ) {
boolean tip = true;
boolean isDeprecated = false;
toolTip.hide();
toolTip.setHideDelay( TOOLTIP_HIDE_DELAY_SHORT );
Point real = screen2real( e.x, e.y );
AreaOwner areaOwner = getVisibleAreaOwner( real.x, real.y );
if ( areaOwner != null && areaOwner.getAreaType() != null ) {
switch ( areaOwner.getAreaType() ) {
case STEP_ICON:
StepMeta stepMeta = (StepMeta) areaOwner.getOwner();
isDeprecated = stepMeta.isDeprecated();
if ( !stepMeta.isMissing() && !mouseOverSteps.contains( stepMeta ) ) {
addStepMouseOverDelayTimer( stepMeta );
redraw();
tip = false;
}
break;
default:
break;
}
}
// Show a tool tip upon mouse-over of an object on the canvas
if ( ( tip && !helpTip.isVisible() ) || isDeprecated ) {
setToolTip( real.x, real.y, e.x, e.y );
}
}
@Override
public void mouseScrolled( MouseEvent e ) {
/*
* if (e.count == 3) { // scroll up zoomIn(); } else if (e.count == -3) { // scroll down zoomOut(); } }
*/
}
private void addCandidateAsHop( int mouseX, int mouseY ) {
boolean forward = startHopStep != null;
StepMeta fromStep = candidate.getFromStep();
StepMeta toStep = candidate.getToStep();
// See what the options are.
// - Does the source step has multiple stream options?
// - Does the target step have multiple input stream options?
//
List<StreamInterface> streams = new ArrayList<>();
StepIOMetaInterface fromIoMeta = fromStep.getStepMetaInterface().getStepIOMeta();
List<StreamInterface> targetStreams = fromIoMeta.getTargetStreams();
if ( forward ) {
streams.addAll( targetStreams );
}
StepIOMetaInterface toIoMeta = toStep.getStepMetaInterface().getStepIOMeta();
List<StreamInterface> infoStreams = toIoMeta.getInfoStreams();
if ( !forward ) {
streams.addAll( infoStreams );
}
if ( forward ) {
if ( fromIoMeta.isOutputProducer() && toStep.equals( currentStep ) ) {
streams.add( new Stream( StreamType.OUTPUT, fromStep, BaseMessages
.getString( PKG, "Spoon.Hop.MainOutputOfStep" ), StreamIcon.OUTPUT, null ) );
}
if ( fromStep.supportsErrorHandling() && toStep.equals( currentStep ) ) {
streams.add( new Stream( StreamType.ERROR, fromStep, BaseMessages.getString( PKG,
"Spoon.Hop.ErrorHandlingOfStep" ), StreamIcon.ERROR, null ) );
}
} else {
if ( toIoMeta.isInputAcceptor() && fromStep.equals( currentStep ) ) {
streams.add( new Stream( StreamType.INPUT, toStep, BaseMessages.getString( PKG, "Spoon.Hop.MainInputOfStep" ),
StreamIcon.INPUT, null ) );
}
if ( fromStep.supportsErrorHandling() && fromStep.equals( currentStep ) ) {
streams.add( new Stream( StreamType.ERROR, fromStep, BaseMessages.getString( PKG,
"Spoon.Hop.ErrorHandlingOfStep" ), StreamIcon.ERROR, null ) );
}
}
// Targets can be dynamically added to this step...
//
if ( forward ) {
streams.addAll( fromStep.getStepMetaInterface().getOptionalStreams() );
} else {
streams.addAll( toStep.getStepMetaInterface().getOptionalStreams() );
}
// Show a list of options on the canvas...
//
if ( streams.size() > 1 ) {
// Show a pop-up menu with all the possible options...
//
Menu menu = new Menu( canvas );
for ( final StreamInterface stream : streams ) {
MenuItem item = new MenuItem( menu, SWT.NONE );
item.setText( Const.NVL( stream.getDescription(), "" ) );
item.setImage( getImageFor( stream ) );
item.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e ) {
addHop( stream );
}
} );
}
menu.setLocation( canvas.toDisplay( mouseX, mouseY ) );
menu.setVisible( true );
return;
}
if ( streams.size() == 1 ) {
addHop( streams.get( 0 ) );
} else {
return;
}
/*
*
* if (transMeta.findTransHop(candidate) == null) { spoon.newHop(transMeta, candidate); } if (startErrorHopStep) {
* addErrorHop(); } if (startTargetHopStream != null) { // Auto-configure the target in the source step... //
* startTargetHopStream.setStepMeta(candidate.getToStep());
* startTargetHopStream.setStepname(candidate.getToStep().getName()); startTargetHopStream = null; }
*/
candidate = null;
selectedSteps = null;
startHopStep = null;
endHopLocation = null;
startErrorHopStep = false;
// redraw();
}
private Image getImageFor( StreamInterface stream ) {
Display disp = shell.getDisplay();
SwtUniversalImage swtImage = SWTGC.getNativeImage( BasePainter.getStreamIconImage( stream.getStreamIcon() ) );
return swtImage.getAsBitmapForSize( disp, ConstUI.SMALL_ICON_SIZE, ConstUI.SMALL_ICON_SIZE );
}
protected void addHop( StreamInterface stream ) {
switch ( stream.getStreamType() ) {
case ERROR:
addErrorHop();
candidate.setErrorHop( true );
spoon.newHop( transMeta, candidate );
break;
case INPUT:
spoon.newHop( transMeta, candidate );
break;
case OUTPUT:
StepErrorMeta stepErrorMeta = candidate.getFromStep().getStepErrorMeta();
if ( stepErrorMeta != null && stepErrorMeta.getTargetStep() != null ) {
if ( stepErrorMeta.getTargetStep().equals( candidate.getToStep() ) ) {
candidate.getFromStep().setStepErrorMeta( null );
}
}
spoon.newHop( transMeta, candidate );
break;
case INFO:
stream.setStepMeta( candidate.getFromStep() );
candidate.getToStep().getStepMetaInterface().handleStreamSelection( stream );
spoon.newHop( transMeta, candidate );
break;
case TARGET:
// We connect a target of the source step to an output step...
//
stream.setStepMeta( candidate.getToStep() );
candidate.getFromStep().getStepMetaInterface().handleStreamSelection( stream );
spoon.newHop( transMeta, candidate );
break;
default:
break;
}
clearSettings();
}
private void addErrorHop() {
// Automatically configure the step error handling too!
//
if ( candidate == null || candidate.getFromStep() == null ) {
return;
}
StepErrorMeta errorMeta = candidate.getFromStep().getStepErrorMeta();
if ( errorMeta == null ) {
errorMeta = new StepErrorMeta( transMeta, candidate.getFromStep() );
}
errorMeta.setEnabled( true );
errorMeta.setTargetStep( candidate.getToStep() );
candidate.getFromStep().setStepErrorMeta( errorMeta );
}
private void resetDelayTimer( StepMeta stepMeta ) {
DelayTimer delayTimer = delayTimers.get( stepMeta );
if ( delayTimer != null ) {
delayTimer.reset();
}
}
/*
* private void showStepTargetOptions(final StepMeta stepMeta, StepIOMetaInterface ioMeta, int x, int y) {
*
* if (!Utils.isEmpty(ioMeta.getTargetStepnames())) { final Menu menu = new Menu(canvas); for (final StreamInterface
* stream : ioMeta.getTargetStreams()) { MenuItem menuItem = new MenuItem(menu, SWT.NONE);
* menuItem.setText(stream.getDescription()); menuItem.addSelectionListener(new SelectionAdapter() {
*
* @Override public void widgetSelected(SelectionEvent arg0) { // Click on the target icon means: create a new target
* hop // if (startHopStep==null) { startHopStep = stepMeta; } menu.setVisible(false); menu.dispose(); redraw(); } });
* } menu.setLocation(x, y); menu.setVisible(true); resetDelayTimer(stepMeta);
*
* //showTargetStreamsStep = stepMeta; } }
*/
@Override
public void mouseEnter( MouseEvent arg0 ) {
}
@Override
public void mouseExit( MouseEvent arg0 ) {
}
private synchronized void addStepMouseOverDelayTimer( final StepMeta stepMeta ) {
// Don't add the same mouse over delay timer twice...
//
if ( mouseOverSteps.contains( stepMeta ) ) {
return;
}
mouseOverSteps.add( stepMeta );
DelayTimer delayTimer = new DelayTimer( 500, new DelayListener() {
@Override
public void expired() {
mouseOverSteps.remove( stepMeta );
delayTimers.remove( stepMeta );
showTargetStreamsStep = null;
asyncRedraw();
}
}, new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
Point cursor = getLastMove();
if ( cursor != null ) {
AreaOwner areaOwner = getVisibleAreaOwner( cursor.x, cursor.y );
if ( areaOwner != null ) {
AreaType areaType = areaOwner.getAreaType();
if ( areaType == AreaType.STEP_ICON ) {
StepMeta selectedStepMeta = (StepMeta) areaOwner.getOwner();
return selectedStepMeta == stepMeta;
} else if ( areaType != null && areaType.belongsToTransContextMenu() ) {
StepMeta selectedStepMeta = (StepMeta) areaOwner.getParent();
return selectedStepMeta == stepMeta;
} else if ( areaOwner.getExtensionAreaType() != null ) {
return true;
}
}
}
return false;
}
} );
new Thread( delayTimer ).start();
delayTimers.put( stepMeta, delayTimer );
}
private void stopStepMouseOverDelayTimer( final StepMeta stepMeta ) {
DelayTimer delayTimer = delayTimers.get( stepMeta );
if ( delayTimer != null ) {
delayTimer.stop();
}
}
private void stopStepMouseOverDelayTimers() {
for ( DelayTimer timer : delayTimers.values() ) {
timer.stop();
}
}
protected void asyncRedraw() {
spoon.getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
if ( !TransGraph.this.isDisposed() ) {
TransGraph.this.redraw();
}
}
} );
}
private void addToolBar() {
try {
toolbar = (XulToolbar) getXulDomContainer().getDocumentRoot().getElementById( "nav-toolbar" );
ToolBar swtToolbar = (ToolBar) toolbar.getManagedObject();
swtToolbar.setBackground( GUIResource.getInstance().getColorDemoGray() );
swtToolbar.pack();
// Added 1/11/2016 to implement dropdown option for "Run"
ToolItem runItem = new ToolItem( swtToolbar, SWT.DROP_DOWN, 0 );
runItem.setImage( GUIResource.getInstance().getImage( "ui/images/run.svg" ) );
runItem.setToolTipText( BaseMessages.getString( PKG, "Spoon.Tooltip.RunTranformation" ) );
runItem.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e ) {
if ( e.detail == SWT.DROP_DOWN ) {
Menu menu = new Menu( shell, SWT.POP_UP );
MenuItem item1 = new MenuItem( menu, SWT.PUSH );
item1.setText( BaseMessages.getString( PKG, "Spoon.Run.Run" ) );
item1.setAccelerator( SWT.F9 );
item1.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e1 ) {
runTransformation();
}
} );
MenuItem item2 = new MenuItem( menu, SWT.PUSH );
item2.setText( BaseMessages.getString( PKG, "Spoon.Run.RunOptions" ) );
item2.setAccelerator( SWT.F8 );
item2.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e2 ) {
runOptionsTransformation();
}
} );
menu.setLocation( shell.getDisplay().map( mainComposite.getParent(), null, mainComposite.getLocation() ) );
menu.setVisible( true );
} else {
runTransformation();
}
}
} );
stopItem = new ToolItem( swtToolbar, SWT.DROP_DOWN, 2 );
stopItem.setImage( GUIResource.getInstance().getImage( "ui/images/stop.svg" ) );
stopItem.setToolTipText( BaseMessages.getString( PKG, "Spoon.Tooltip.StopTranformation" ) );
stopItem.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e ) {
if ( e.detail == SWT.DROP_DOWN ) {
Menu menu = new Menu( shell, SWT.POP_UP );
MenuItem item1 = new MenuItem( menu, SWT.PUSH );
item1.setText( BaseMessages.getString( PKG, "Spoon.Menu.StopTranformation" ) );
item1.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e1 ) {
stopTransformation();
}
} );
MenuItem item2 = new MenuItem( menu, SWT.PUSH );
item2.setText( BaseMessages.getString( PKG, "Spoon.Menu.SafeStopTranformation" ) );
item2.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e2 ) {
safeStop();
}
} );
menu.setLocation( shell.getDisplay().map( mainComposite.getParent(), null, mainComposite.getLocation() ) );
menu.setVisible( true );
} else {
stopTransformation();
}
}
} );
// Hack alert : more XUL limitations...
// TODO: no longer a limitation use toolbaritem
//
ToolItem sep = new ToolItem( swtToolbar, SWT.SEPARATOR );
zoomLabel = new Combo( swtToolbar, SWT.DROP_DOWN );
zoomLabel.setItems( TransPainter.magnificationDescriptions );
zoomLabel.addSelectionListener( new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent arg0 ) {
readMagnification();
}
} );
zoomLabel.addKeyListener( new KeyAdapter() {
@Override
public void keyPressed( KeyEvent event ) {
if ( event.character == SWT.CR ) {
readMagnification();
}
}
} );
setZoomLabel();
zoomLabel.pack();
sep.setWidth( 80 );
sep.setControl( zoomLabel );
swtToolbar.pack();
} catch ( Throwable t ) {
log.logError( "Error loading the navigation toolbar for Spoon", t );
new ErrorDialog( shell, BaseMessages.getString( PKG, "Spoon.Exception.ErrorReadingXULFile.Title" ), BaseMessages
.getString( PKG, "Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_TRANS_TOOLBAR ), new Exception( t ) );
}
}
/**
* Allows for magnifying to any percentage entered by the user...
*/
private void readMagnification() {
String possibleText = zoomLabel.getText();
possibleText = possibleText.replace( "%", "" );
float possibleFloatMagnification;
try {
possibleFloatMagnification = Float.parseFloat( possibleText ) / 100;
magnification = possibleFloatMagnification;
if ( zoomLabel.getText().indexOf( '%' ) < 0 ) {
zoomLabel.setText( zoomLabel.getText().concat( "%" ) );
}
} catch ( Exception e ) {
modalMessageDialog( getString( "TransGraph.Dialog.InvalidZoomMeasurement.Title" ),
getString( "TransGraph.Dialog.InvalidZoomMeasurement.Message", zoomLabel.getText() ),
SWT.YES | SWT.ICON_ERROR );
}
redraw();
}
protected void hideToolTips() {
toolTip.hide();
helpTip.hide();
toolTip.setHideDelay( TOOLTIP_HIDE_DELAY_SHORT );
}
private void showHelpTip( int x, int y, String tipTitle, String tipMessage ) {
helpTip.setTitle( tipTitle );
helpTip.setMessage( tipMessage.replaceAll( "\n", Const.CR ) );
helpTip
.setCheckBoxMessage( BaseMessages.getString( PKG, "TransGraph.HelpToolTip.DoNotShowAnyMoreCheckBox.Message" ) );
// helpTip.hide();
// int iconSize = spoon.props.getIconSize();
org.eclipse.swt.graphics.Point location = new org.eclipse.swt.graphics.Point( x - 5, y - 5 );
helpTip.show( location );
}
/**
* Select all the steps in a certain (screen) rectangle
*
* @param rect The selection area as a rectangle
*/
public void selectInRect( TransMeta transMeta, org.pentaho.di.core.gui.Rectangle rect ) {
if ( rect.height < 0 || rect.width < 0 ) {
org.pentaho.di.core.gui.Rectangle rectified =
new org.pentaho.di.core.gui.Rectangle( rect.x, rect.y, rect.width, rect.height );
// Only for people not dragging from left top to right bottom
if ( rectified.height < 0 ) {
rectified.y = rectified.y + rectified.height;
rectified.height = -rectified.height;
}
if ( rectified.width < 0 ) {
rectified.x = rectified.x + rectified.width;
rectified.width = -rectified.width;
}
rect = rectified;
}
for ( int i = 0; i < transMeta.nrSteps(); i++ ) {
StepMeta stepMeta = transMeta.getStep( i );
Point a = stepMeta.getLocation();
if ( rect.contains( a.x, a.y ) ) {
stepMeta.setSelected( true );
}
}
for ( int i = 0; i < transMeta.nrNotes(); i++ ) {
NotePadMeta ni = transMeta.getNote( i );
Point a = ni.getLocation();
Point b = new Point( a.x + ni.width, a.y + ni.height );
if ( rect.contains( a.x, a.y ) && rect.contains( b.x, b.y ) ) {
ni.setSelected( true );
}
}
}
@Override
public void keyPressed( KeyEvent e ) {
if ( e.keyCode == SWT.ESC ) {
clearSettings();
redraw();
}
if ( e.keyCode == SWT.DEL ) {
List<StepMeta> stepMeta = transMeta.getSelectedSteps();
if ( stepMeta != null && stepMeta.size() > 0 ) {
delSelected( null );
}
}
if ( e.keyCode == SWT.F1 ) {
spoon.browseVersionHistory();
}
if ( e.keyCode == SWT.F2 ) {
spoon.editKettlePropertiesFile();
}
// CTRL-UP : allignTop();
if ( e.keyCode == SWT.ARROW_UP && ( e.stateMask & SWT.MOD1 ) != 0 ) {
alligntop();
}
// CTRL-DOWN : allignBottom();
if ( e.keyCode == SWT.ARROW_DOWN && ( e.stateMask & SWT.MOD1 ) != 0 ) {
allignbottom();
}
// CTRL-LEFT : allignleft();
if ( e.keyCode == SWT.ARROW_LEFT && ( e.stateMask & SWT.MOD1 ) != 0 ) {
allignleft();
}
// CTRL-RIGHT : allignRight();
if ( e.keyCode == SWT.ARROW_RIGHT && ( e.stateMask & SWT.MOD1 ) != 0 ) {
allignright();
}
// ALT-RIGHT : distributeHorizontal();
if ( e.keyCode == SWT.ARROW_RIGHT && ( e.stateMask & SWT.ALT ) != 0 ) {
distributehorizontal();
}
// ALT-UP : distributeVertical();
if ( e.keyCode == SWT.ARROW_UP && ( e.stateMask & SWT.ALT ) != 0 ) {
distributevertical();
}
// ALT-HOME : snap to grid
if ( e.keyCode == SWT.HOME && ( e.stateMask & SWT.ALT ) != 0 ) {
snaptogrid( ConstUI.GRID_SIZE );
}
if ( e.character == 'E' && ( e.stateMask & SWT.CTRL ) != 0 ) {
checkErrorVisuals();
}
// CTRL-W or CTRL-F4 : close tab
if ( ( e.keyCode == 'w' && ( e.stateMask & SWT.MOD1 ) != 0 )
|| ( e.keyCode == SWT.F4 && ( e.stateMask & SWT.MOD1 ) != 0 ) ) {
spoon.tabCloseSelected();
}
// Auto-layout
if ( e.character == 'A' ) {
autoLayout();
}
// SPACE : over a step: show output fields...
if ( e.character == ' ' && lastMove != null ) {
Point real = lastMove;
// Hide the tooltip!
hideToolTips();
// Set the pop-up menu
StepMeta stepMeta = transMeta.getStep( real.x, real.y, iconsize );
if ( stepMeta != null ) {
// OK, we found a step, show the output fields...
inputOutputFields( stepMeta, false );
}
}
}
@Override
public void keyReleased( KeyEvent e ) {
}
public void renameStep( StepMeta stepMeta, String stepname ) {
String newname = stepname;
StepMeta smeta = transMeta.findStep( newname, stepMeta );
int nr = 2;
while ( smeta != null ) {
newname = stepname + " " + nr;
smeta = transMeta.findStep( newname );
nr++;
}
if ( nr > 2 ) {
stepname = newname;
modalMessageDialog( getString( "Spoon.Dialog.StepnameExists.Title" ),
getString( "Spoon.Dialog.StepnameExists.Message", stepname ), SWT.OK | SWT.ICON_INFORMATION );
}
stepMeta.setName( stepname );
stepMeta.setChanged();
spoon.refreshTree(); // to reflect the new name
spoon.refreshGraph();
}
public void clearSettings() {
selectedStep = null;
noInputStep = null;
selectedNote = null;
selectedSteps = null;
selectionRegion = null;
candidate = null;
last_hop_split = null;
lastButton = 0;
iconoffset = null;
startHopStep = null;
endHopStep = null;
endHopLocation = null;
mouseOverSteps.clear();
for ( int i = 0; i < transMeta.nrTransHops(); i++ ) {
// CHECKSTYLE:Indentation:OFF
transMeta.getTransHop( i ).split = false;
}
stopStepMouseOverDelayTimers();
}
public String[] getDropStrings( String str, String sep ) {
StringTokenizer strtok = new StringTokenizer( str, sep );
String[] retval = new String[ strtok.countTokens() ];
int i = 0;
while ( strtok.hasMoreElements() ) {
retval[ i ] = strtok.nextToken();
i++;
}
return retval;
}
public Point getRealPosition( Composite canvas, int x, int y ) {
Point p = new Point( 0, 0 );
Composite follow = canvas;
while ( follow != null ) {
org.eclipse.swt.graphics.Point loc = follow.getLocation();
Point xy = new Point( loc.x, loc.y );
p.x += xy.x;
p.y += xy.y;
follow = follow.getParent();
}
int offsetX = -16;
int offsetY = -64;
if ( Const.isOSX() ) {
offsetX = -2;
offsetY = -24;
}
p.x = x - p.x + offsetX;
p.y = y - p.y + offsetY;
return screen2real( p.x, p.y );
}
/**
* See if location (x,y) is on a line between two steps: the hop!
*
* @param x
* @param y
* @return the transformation hop on the specified location, otherwise: null
*/
protected TransHopMeta findHop( int x, int y ) {
return findHop( x, y, null );
}
/**
* See if location (x,y) is on a line between two steps: the hop!
*
* @param x
* @param y
* @param exclude the step to exclude from the hops (from or to location). Specify null if no step is to be excluded.
* @return the transformation hop on the specified location, otherwise: null
*/
private TransHopMeta findHop( int x, int y, StepMeta exclude ) {
int i;
TransHopMeta online = null;
for ( i = 0; i < transMeta.nrTransHops(); i++ ) {
TransHopMeta hi = transMeta.getTransHop( i );
StepMeta fs = hi.getFromStep();
StepMeta ts = hi.getToStep();
if ( fs == null || ts == null ) {
return null;
}
// If either the "from" or "to" step is excluded, skip this hop.
//
if ( exclude != null && ( exclude.equals( fs ) || exclude.equals( ts ) ) ) {
continue;
}
int[] line = getLine( fs, ts );
if ( pointOnLine( x, y, line ) ) {
online = hi;
}
}
return online;
}
private int[] getLine( StepMeta fs, StepMeta ts ) {
Point from = fs.getLocation();
Point to = ts.getLocation();
offset = getOffset();
int x1 = from.x + iconsize / 2;
int y1 = from.y + iconsize / 2;
int x2 = to.x + iconsize / 2;
int y2 = to.y + iconsize / 2;
return new int[] { x1, y1, x2, y2 };
}
public void hideStep() {
for ( int i = 0; i < transMeta.nrSteps(); i++ ) {
StepMeta sti = transMeta.getStep( i );
if ( sti.isDrawn() && sti.isSelected() ) {
sti.hideStep();
spoon.refreshTree();
}
}
getCurrentStep().hideStep();
spoon.refreshTree();
redraw();
}
public void checkSelectedSteps() {
spoon.checkTrans( transMeta, true );
}
public void detachStep() {
detach( getCurrentStep() );
selectedSteps = null;
}
public void generateMappingToThisStep() {
spoon.generateFieldMapping( transMeta, getCurrentStep() );
}
public void partitioning() {
spoon.editPartitioning( transMeta, getCurrentStep() );
}
public void clustering() {
List<StepMeta> selected = transMeta.getSelectedSteps();
if ( selected != null && selected.size() > 0 ) {
spoon.editClustering( transMeta, transMeta.getSelectedSteps() );
} else {
spoon.editClustering( transMeta, getCurrentStep() );
}
}
public void errorHandling() {
spoon.editStepErrorHandling( transMeta, getCurrentStep() );
}
public void newHopChoice() {
selectedSteps = null;
newHop();
}
public void editStep() {
selectedSteps = null;
editStep( getCurrentStep() );
}
public void editDescription() {
editDescription( getCurrentStep() );
}
public void setDistributes() {
getCurrentStep().setDistributes( true );
getCurrentStep().setRowDistribution( null );
spoon.refreshGraph();
spoon.refreshTree();
}
public void setCustomRowDistribution() {
// TODO: ask user which row distribution is needed...
//
RowDistributionInterface rowDistribution = askUserForCustomDistributionMethod();
getCurrentStep().setDistributes( true );
getCurrentStep().setRowDistribution( rowDistribution );
spoon.refreshGraph();
spoon.refreshTree();
}
public RowDistributionInterface askUserForCustomDistributionMethod() {
List<PluginInterface> plugins = PluginRegistry.getInstance().getPlugins( RowDistributionPluginType.class );
if ( Utils.isEmpty( plugins ) ) {
return null;
}
List<String> choices = new ArrayList<>();
for ( PluginInterface plugin : plugins ) {
choices.add( plugin.getName() + " : " + plugin.getDescription() );
}
EnterSelectionDialog dialog =
new EnterSelectionDialog( shell, choices.toArray( new String[ choices.size() ] ), "Select distribution method",
"Please select the row distribution method:" );
if ( dialog.open() != null ) {
PluginInterface plugin = plugins.get( dialog.getSelectionNr() );
try {
return (RowDistributionInterface) PluginRegistry.getInstance().loadClass( plugin );
} catch ( Exception e ) {
new ErrorDialog( shell, "Error", "Error loading row distribution plugin class", e );
return null;
}
} else {
return null;
}
}
public void setCopies() {
getCurrentStep().setDistributes( false );
spoon.refreshGraph();
spoon.refreshTree();
}
public void copies() {
copies( getCurrentStep() );
}
public void copies( StepMeta stepMeta ) {
final boolean multipleOK = checkNumberOfCopies( transMeta, stepMeta );
selectedSteps = null;
String tt = BaseMessages.getString( PKG, "TransGraph.Dialog.NrOfCopiesOfStep.Title" );
String mt = BaseMessages.getString( PKG, "TransGraph.Dialog.NrOfCopiesOfStep.Message" );
EnterStringDialog nd = new EnterStringDialog( shell, stepMeta.getCopiesString(), tt, mt, true, transMeta );
String cop = nd.open();
if ( !Utils.isEmpty( cop ) ) {
int copies = Const.toInt( transMeta.environmentSubstitute( cop ), -1 );
if ( copies > 1 && !multipleOK ) {
cop = "1";
modalMessageDialog( getString( "TransGraph.Dialog.MultipleCopiesAreNotAllowedHere.Title" ),
getString( "TransGraph.Dialog.MultipleCopiesAreNotAllowedHere.Message" ), SWT.YES | SWT.ICON_WARNING );
}
String cps = stepMeta.getCopiesString();
if ( ( cps != null && !cps.equals( cop ) ) || ( cps == null && cop != null ) ) {
stepMeta.setChanged();
}
stepMeta.setCopiesString( cop );
spoon.refreshGraph();
}
}
public void dupeStep() {
try {
List<StepMeta> steps = transMeta.getSelectedSteps();
if ( steps.size() <= 1 ) {
spoon.dupeStep( transMeta, getCurrentStep() );
} else {
for ( StepMeta stepMeta : steps ) {
spoon.dupeStep( transMeta, stepMeta );
}
}
} catch ( Exception ex ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "TransGraph.Dialog.ErrorDuplicatingStep.Title" ),
BaseMessages.getString( PKG, "TransGraph.Dialog.ErrorDuplicatingStep.Message" ), ex );
}
}
public void copyStep() {
spoon.copySelected( transMeta, transMeta.getSelectedSteps(), transMeta.getSelectedNotes() );
}
public void delSelected() {
delSelected( getCurrentStep() );
}
public void fieldsBefore() {
selectedSteps = null;
inputOutputFields( getCurrentStep(), true );
}
public void fieldsAfter() {
selectedSteps = null;
inputOutputFields( getCurrentStep(), false );
}
public void fieldsLineage() {
TransDataLineage tdl = new TransDataLineage( transMeta );
try {
tdl.calculateLineage();
} catch ( Exception e ) {
new ErrorDialog( shell, "Lineage error", "Unexpected lineage calculation error", e );
}
}
public void editHop() {
selectionRegion = null;
editHop( getCurrentHop() );
}
public void flipHopDirection() {
selectionRegion = null;
TransHopMeta hi = getCurrentHop();
hi.flip();
if ( transMeta.hasLoop( hi.getToStep() ) ) {
spoon.refreshGraph();
modalMessageDialog( getString( "TransGraph.Dialog.LoopsAreNotAllowed.Title" ),
getString( "TransGraph.Dialog.LoopsAreNotAllowed.Message" ), SWT.OK | SWT.ICON_ERROR );
hi.flip();
spoon.refreshGraph();
} else {
hi.setChanged();
spoon.refreshGraph();
spoon.refreshTree();
spoon.setShellText();
}
}
public void enableHop() {
selectionRegion = null;
TransHopMeta hi = getCurrentHop();
TransHopMeta before = (TransHopMeta) hi.clone();
setHopEnabled( hi, !hi.isEnabled() );
if ( hi.isEnabled() && transMeta.hasLoop( hi.getToStep() ) ) {
setHopEnabled( hi, false );
modalMessageDialog( getString( "TransGraph.Dialog.LoopAfterHopEnabled.Title" ),
getString( "TransGraph.Dialog.LoopAfterHopEnabled.Message" ), SWT.OK | SWT.ICON_ERROR );
} else {
TransHopMeta after = (TransHopMeta) hi.clone();
spoon.addUndoChange( transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after },
new int[] { transMeta.indexOfTransHop( hi ) } );
spoon.refreshGraph();
spoon.refreshTree();
}
updateErrorMetaForHop( hi );
}
public void deleteHop() {
selectionRegion = null;
TransHopMeta hi = getCurrentHop();
spoon.delHop( transMeta, hi );
}
private void updateErrorMetaForHop( TransHopMeta hop ) {
if ( hop != null && hop.isErrorHop() ) {
StepErrorMeta errorMeta = hop.getFromStep().getStepErrorMeta();
if ( errorMeta != null ) {
errorMeta.setEnabled( hop.isEnabled() );
}
}
}
public void enableHopsBetweenSelectedSteps() {
enableHopsBetweenSelectedSteps( true );
}
public void disableHopsBetweenSelectedSteps() {
enableHopsBetweenSelectedSteps( false );
}
/**
* This method enables or disables all the hops between the selected steps.
**/
public void enableHopsBetweenSelectedSteps( boolean enabled ) {
List<StepMeta> list = transMeta.getSelectedSteps();
boolean hasLoop = false;
for ( int i = 0; i < transMeta.nrTransHops(); i++ ) {
TransHopMeta hop = transMeta.getTransHop( i );
if ( list.contains( hop.getFromStep() ) && list.contains( hop.getToStep() ) ) {
TransHopMeta before = (TransHopMeta) hop.clone();
setHopEnabled( hop, enabled );
TransHopMeta after = (TransHopMeta) hop.clone();
spoon.addUndoChange( transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after },
new int[] { transMeta.indexOfTransHop( hop ) } );
if ( transMeta.hasLoop( hop.getToStep() ) ) {
hasLoop = true;
setHopEnabled( hop, false );
}
}
}
if ( enabled && hasLoop ) {
modalMessageDialog( getString( "TransGraph.Dialog.HopCausesLoop.Title" ),
getString( "TransGraph.Dialog.HopCausesLoop.Message" ), SWT.OK | SWT.ICON_ERROR );
}
spoon.refreshGraph();
}
public void enableHopsDownstream() {
enableDisableHopsDownstream( true );
}
public void disableHopsDownstream() {
enableDisableHopsDownstream( false );
}
public void enableDisableHopsDownstream( boolean enabled ) {
if ( currentHop == null ) {
return;
}
TransHopMeta before = (TransHopMeta) currentHop.clone();
setHopEnabled( currentHop, enabled );
TransHopMeta after = (TransHopMeta) currentHop.clone();
spoon.addUndoChange( transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta
.indexOfTransHop( currentHop ) } );
Set<StepMeta> checkedEntries = enableDisableNextHops( currentHop.getToStep(), enabled, new HashSet<>() );
if ( checkedEntries.stream().anyMatch( entry -> transMeta.hasLoop( entry ) ) ) {
modalMessageDialog( getString( "TransGraph.Dialog.HopCausesLoop.Title" ),
getString( "TransGraph.Dialog.HopCausesLoop.Message" ), SWT.OK | SWT.ICON_ERROR );
}
spoon.refreshGraph();
}
private Set<StepMeta> enableDisableNextHops( StepMeta from, boolean enabled, Set<StepMeta> checkedEntries ) {
checkedEntries.add( from );
transMeta.getTransHops().stream()
.filter( hop -> from.equals( hop.getFromStep() ) )
.forEach( hop -> {
if ( hop.isEnabled() != enabled ) {
TransHopMeta before = (TransHopMeta) hop.clone();
setHopEnabled( hop, enabled );
TransHopMeta after = (TransHopMeta) hop.clone();
spoon.addUndoChange( transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after },
new int[] { transMeta
.indexOfTransHop( hop ) } );
}
if ( !checkedEntries.contains( hop.getToStep() ) ) {
enableDisableNextHops( hop.getToStep(), enabled, checkedEntries );
}
} );
return checkedEntries;
}
public void editNote() {
selectionRegion = null;
editNote( getCurrentNote() );
}
public void deleteNote() {
selectionRegion = null;
int idx = transMeta.indexOfNote( ni );
if ( idx >= 0 ) {
transMeta.removeNote( idx );
spoon.addUndoDelete( transMeta, new NotePadMeta[] { (NotePadMeta) ni.clone() }, new int[] { idx } );
redraw();
}
}
public void raiseNote() {
selectionRegion = null;
int idx = transMeta.indexOfNote( getCurrentNote() );
if ( idx >= 0 ) {
transMeta.raiseNote( idx );
// TBD: spoon.addUndoRaise(transMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void lowerNote() {
selectionRegion = null;
int idx = transMeta.indexOfNote( getCurrentNote() );
if ( idx >= 0 ) {
transMeta.lowerNote( idx );
// TBD: spoon.addUndoLower(transMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void newNote() {
selectionRegion = null;
String title = BaseMessages.getString( PKG, "TransGraph.Dialog.NoteEditor.Title" );
NotePadDialog dd = new NotePadDialog( transMeta, shell, title );
NotePadMeta n = dd.open();
if ( n != null ) {
NotePadMeta npi =
new NotePadMeta( n.getNote(), lastclick.x, lastclick.y, ConstUI.NOTE_MIN_SIZE, ConstUI.NOTE_MIN_SIZE, n
.getFontName(), n.getFontSize(), n.isFontBold(), n.isFontItalic(), n.getFontColorRed(), n
.getFontColorGreen(), n.getFontColorBlue(), n.getBackGroundColorRed(), n.getBackGroundColorGreen(), n
.getBackGroundColorBlue(), n.getBorderColorRed(), n.getBorderColorGreen(), n.getBorderColorBlue(), n
.isDrawShadow() );
transMeta.addNote( npi );
spoon.addUndoNew( transMeta, new NotePadMeta[] { npi }, new int[] { transMeta.indexOfNote( npi ) } );
redraw();
}
}
public void paste() {
final String clipcontent = spoon.fromClipboard();
Point loc = new Point( currentMouseX, currentMouseY );
spoon.pasteXML( transMeta, clipcontent, loc );
}
public void settings() {
editProperties( transMeta, spoon, spoon.getRepository(), true );
}
public void newStep( String description ) {
StepMeta stepMeta = spoon.newStep( transMeta, description, description, false, true );
PropsUI.setLocation( stepMeta, currentMouseX, currentMouseY );
stepMeta.setDraw( true );
redraw();
}
/**
* This sets the popup-menu on the background of the canvas based on the xy coordinate of the mouse. This method is
* called after a mouse-click.
*
* @param x X-coordinate on screen
* @param y Y-coordinate on screen
*/
private synchronized void setMenu( int x, int y ) {
try {
currentMouseX = x;
currentMouseY = y;
final StepMeta stepMeta = transMeta.getStep( x, y, iconsize );
if ( stepMeta != null ) { // We clicked on a Step!
setCurrentStep( stepMeta );
XulMenupopup menu = menuMap.get( "trans-graph-entry" );
try {
ExtensionPointHandler.callExtensionPoint( LogChannel.GENERAL, KettleExtensionPoint.TransStepRightClick.id,
new StepMenuExtension( this, menu ) );
} catch ( Exception ex ) {
LogChannel.GENERAL.logError( "Error calling TransStepRightClick extension point", ex );
}
if ( menu != null ) {
List<StepMeta> selection = transMeta.getSelectedSteps();
doRightClickSelection( stepMeta, selection );
int sels = selection.size();
Document doc = getXulDomContainer().getDocumentRoot();
// TODO: cache the next line (seems fast enough)?
//
List<PluginInterface> rowDistributionPlugins =
PluginRegistry.getInstance().getPlugins( RowDistributionPluginType.class );
JfaceMenupopup customRowDistMenu =
(JfaceMenupopup) doc.getElementById( "trans-graph-entry-data-movement-popup" );
customRowDistMenu.setDisabled( false );
customRowDistMenu.removeChildren();
// Add the default round robin plugin...
//
Action action = new Action( "RoundRobinRowDistribution", Action.AS_CHECK_BOX ) {
@Override
public void run() {
stepMeta.setRowDistribution( null ); // default
stepMeta.setDistributes( true );
}
};
boolean selected = stepMeta.isDistributes() && stepMeta.getRowDistribution() == null;
action.setChecked( selected );
JfaceMenuitem child =
new JfaceMenuitem( null, customRowDistMenu, xulDomContainer, "Round Robin row distribution", 0, action );
child.setLabel( BaseMessages.getString( PKG, "TransGraph.PopupMenu.RoundRobin" ) );
child.setDisabled( false );
child.setSelected( selected );
for ( int p = 0; p < rowDistributionPlugins.size(); p++ ) {
final PluginInterface rowDistributionPlugin = rowDistributionPlugins.get( p );
selected =
stepMeta.isDistributes() && stepMeta.getRowDistribution() != null
&& stepMeta.getRowDistribution().getCode().equals( rowDistributionPlugin.getIds()[ 0 ] );
action = new Action( rowDistributionPlugin.getIds()[ 0 ], Action.AS_CHECK_BOX ) {
@Override
public void run() {
try {
stepMeta.setRowDistribution( (RowDistributionInterface) PluginRegistry.getInstance().loadClass(
rowDistributionPlugin ) );
} catch ( Exception e ) {
LogChannel.GENERAL.logError( "Error loading row distribution plugin class: ", e );
}
}
};
action.setChecked( selected );
child =
new JfaceMenuitem( null, customRowDistMenu, xulDomContainer, rowDistributionPlugin.getName(), p + 1,
action );
child.setLabel( rowDistributionPlugin.getName() );
child.setDisabled( false );
child.setSelected( selected );
}
// Add the default copy rows plugin...
//
action = new Action( "CopyRowsDistribution", Action.AS_CHECK_BOX ) {
@Override
public void run() {
stepMeta.setDistributes( false );
}
};
selected = !stepMeta.isDistributes();
action.setChecked( selected );
child = new JfaceMenuitem( null, customRowDistMenu, xulDomContainer, "Copy rows distribution", 0, action );
child.setLabel( BaseMessages.getString( PKG, "TransGraph.PopupMenu.CopyData" ) );
child.setDisabled( false );
child.setSelected( selected );
JfaceMenupopup launchMenu = (JfaceMenupopup) doc.getElementById( "trans-graph-entry-launch-popup" );
String[] referencedObjects = stepMeta.getStepMetaInterface().getReferencedObjectDescriptions();
boolean[] enabledObjects = stepMeta.getStepMetaInterface().isReferencedObjectEnabled();
launchMenu.setDisabled( Utils.isEmpty( referencedObjects ) );
launchMenu.removeChildren();
int childIndex = 0;
// First see if we need to add a special "active" entry (running transformation)
//
StepMetaInterface stepMetaInterface = stepMeta.getStepMetaInterface();
String activeReferencedObjectDescription = stepMetaInterface.getActiveReferencedObjectDescription();
if ( getActiveSubtransformation( this, stepMeta ) != null && activeReferencedObjectDescription != null ) {
action = new Action( activeReferencedObjectDescription, Action.AS_PUSH_BUTTON ) {
@Override
public void run() {
openMapping( stepMeta, -1 ); // negative by convention
}
};
child =
new JfaceMenuitem( null, launchMenu, xulDomContainer, activeReferencedObjectDescription, childIndex++,
action );
child.setLabel( activeReferencedObjectDescription );
child.setDisabled( false );
}
if ( !Utils.isEmpty( referencedObjects ) ) {
for ( int i = 0; i < referencedObjects.length; i++ ) {
final int index = i;
String referencedObject = referencedObjects[ i ];
action = new Action( referencedObject, Action.AS_PUSH_BUTTON ) {
@Override
public void run() {
openMapping( stepMeta, index );
}
};
child = new JfaceMenuitem( null, launchMenu, xulDomContainer, referencedObject, childIndex++, action );
child.setLabel( referencedObject );
child.setDisabled( !enabledObjects[ i ] );
}
}
initializeXulMenu( doc, selection, stepMeta );
ConstUI.displayMenu( menu, canvas );
}
} else {
final TransHopMeta hi = findHop( x, y );
if ( hi != null ) { // We clicked on a HOP!
XulMenupopup menu = menuMap.get( "trans-graph-hop" );
if ( menu != null ) {
setCurrentHop( hi );
XulMenuitem item =
(XulMenuitem) getXulDomContainer().getDocumentRoot().getElementById( "trans-graph-hop-enabled" );
if ( item != null ) {
if ( hi.isEnabled() ) {
item.setLabel( BaseMessages.getString( PKG, "TransGraph.PopupMenu.DisableHop" ) );
} else {
item.setLabel( BaseMessages.getString( PKG, "TransGraph.PopupMenu.EnableHop" ) );
}
}
ConstUI.displayMenu( menu, canvas );
}
} else {
// Clicked on the background: maybe we hit a note?
final NotePadMeta ni = transMeta.getNote( x, y );
setCurrentNote( ni );
if ( ni != null ) {
XulMenupopup menu = menuMap.get( "trans-graph-note" );
if ( menu != null ) {
ConstUI.displayMenu( menu, canvas );
}
} else {
XulMenupopup menu = menuMap.get( "trans-graph-background" );
if ( menu != null ) {
final String clipcontent = spoon.fromClipboard();
XulMenuitem item =
(XulMenuitem) getXulDomContainer().getDocumentRoot().getElementById( "trans-graph-background-paste" );
if ( item != null ) {
item.setDisabled( clipcontent == null );
}
ConstUI.displayMenu( menu, canvas );
}
}
}
}
} catch ( Throwable t ) {
// TODO: fix this: log somehow, is IGNORED for now.
t.printStackTrace();
}
}
public void selectAll() {
spoon.editSelectAll();
}
public void clearSelection() {
spoon.editUnselectAll();
}
protected void initializeXulMenu( Document doc, List<StepMeta> selection, StepMeta stepMeta ) throws KettleException {
XulMenuitem item = (XulMenuitem) doc.getElementById( "trans-graph-entry-newhop" );
int sels = selection.size();
item.setDisabled( sels != 2 );
item = (XulMenuitem) doc.getElementById( "trans-graph-entry-align-snap" );
item.setAcceltext( "ALT-HOME" );
item.setLabel( BaseMessages.getString( PKG, "TransGraph.PopupMenu.SnapToGrid" ) );
item.setAccesskey( "alt-home" );
item = (XulMenuitem) doc.getElementById( "trans-graph-entry-open-mapping" );
XulMenu men = (XulMenu) doc.getElementById( TRANS_GRAPH_ENTRY_SNIFF );
men.setDisabled( trans == null || trans.isRunning() == false );
item = (XulMenuitem) doc.getElementById( "trans-graph-entry-sniff-input" );
item.setDisabled( trans == null || trans.isRunning() == false );
item = (XulMenuitem) doc.getElementById( "trans-graph-entry-sniff-output" );
item.setDisabled( trans == null || trans.isRunning() == false );
item = (XulMenuitem) doc.getElementById( "trans-graph-entry-sniff-error" );
item.setDisabled( !( stepMeta.supportsErrorHandling() && stepMeta.getStepErrorMeta() != null
&& stepMeta.getStepErrorMeta().getTargetStep() != null && trans != null && trans.isRunning() ) );
XulMenu aMenu = (XulMenu) doc.getElementById( TRANS_GRAPH_ENTRY_AGAIN );
if ( aMenu != null ) {
aMenu.setDisabled( sels < 2 );
}
// item = (XulMenuitem) doc.getElementById("trans-graph-entry-data-movement-distribute");
// item.setSelected(stepMeta.isDistributes());
item = (XulMenuitem) doc.getElementById( "trans-graph-entry-partitioning" );
item.setDisabled( spoon.getPartitionSchemasNames( transMeta ).isEmpty() );
item = (XulMenuitem) doc.getElementById( "trans-graph-entry-data-movement-copy" );
item.setSelected( !stepMeta.isDistributes() );
item = (XulMenuitem) doc.getElementById( "trans-graph-entry-hide" );
item.setDisabled( !( stepMeta.isDrawn() && !transMeta.isAnySelectedStepUsedInTransHops() ) );
item = (XulMenuitem) doc.getElementById( "trans-graph-entry-detach" );
item.setDisabled( !transMeta.isStepUsedInTransHops( stepMeta ) );
item = (XulMenuitem) doc.getElementById( "trans-graph-entry-errors" );
item.setDisabled( !stepMeta.supportsErrorHandling() );
}
private boolean checkNumberOfCopies( TransMeta transMeta, StepMeta stepMeta ) {
boolean enabled = true;
List<StepMeta> prevSteps = transMeta.findPreviousSteps( stepMeta );
for ( StepMeta prevStep : prevSteps ) {
// See what the target steps are.
// If one of the target steps is our original step, we can't start multiple copies
//
String[] targetSteps = prevStep.getStepMetaInterface().getStepIOMeta().getTargetStepnames();
if ( targetSteps != null ) {
for ( int t = 0; t < targetSteps.length && enabled; t++ ) {
if ( !Utils.isEmpty( targetSteps[ t ] ) && targetSteps[ t ].equalsIgnoreCase( stepMeta.getName() ) ) {
enabled = false;
}
}
}
}
return enabled;
}
private AreaOwner setToolTip( int x, int y, int screenX, int screenY ) {
AreaOwner subject = null;
if ( !spoon.getProperties().showToolTips() ) {
return subject;
}
canvas.setToolTipText( null );
String newTip = null;
Image tipImage = null;
final TransHopMeta hi = findHop( x, y );
// check the area owner list...
//
StringBuilder tip = new StringBuilder();
AreaOwner areaOwner = getVisibleAreaOwner( x, y );
AreaType areaType = null;
if ( areaOwner != null && areaOwner.getAreaType() != null ) {
areaType = areaOwner.getAreaType();
switch ( areaType ) {
case REMOTE_INPUT_STEP:
StepMeta step = (StepMeta) areaOwner.getParent();
tip.append( "Remote input steps:" ).append( Const.CR ).append( "-----------------------" ).append( Const.CR );
for ( RemoteStep remoteStep : step.getRemoteInputSteps() ) {
tip.append( remoteStep.toString() ).append( Const.CR );
}
break;
case REMOTE_OUTPUT_STEP:
step = (StepMeta) areaOwner.getParent();
tip.append( "Remote output steps:" ).append( Const.CR ).append( "-----------------------" )
.append( Const.CR );
for ( RemoteStep remoteStep : step.getRemoteOutputSteps() ) {
tip.append( remoteStep.toString() ).append( Const.CR );
}
break;
case STEP_PARTITIONING:
step = (StepMeta) areaOwner.getParent();
tip.append( "Step partitioning:" ).append( Const.CR ).append( "-----------------------" ).append( Const.CR );
tip.append( step.getStepPartitioningMeta().toString() ).append( Const.CR );
if ( step.getTargetStepPartitioningMeta() != null ) {
tip.append( Const.CR ).append( Const.CR ).append(
"TARGET: " + step.getTargetStepPartitioningMeta().toString() ).append( Const.CR );
}
break;
case STEP_ERROR_ICON:
String log = (String) areaOwner.getParent();
tip.append( log );
tipImage = GUIResource.getInstance().getImageStepError();
break;
case STEP_ERROR_RED_ICON:
String redLog = (String) areaOwner.getParent();
tip.append( redLog );
tipImage = GUIResource.getInstance().getImageRedStepError();
break;
case HOP_COPY_ICON:
step = (StepMeta) areaOwner.getParent();
tip.append( BaseMessages.getString( PKG, "TransGraph.Hop.Tooltip.HopTypeCopy", step.getName(), Const.CR ) );
tipImage = GUIResource.getInstance().getImageCopyHop();
break;
case ROW_DISTRIBUTION_ICON:
step = (StepMeta) areaOwner.getParent();
tip.append( BaseMessages.getString( PKG, "TransGraph.Hop.Tooltip.RowDistribution", step.getName(), step
.getRowDistribution() == null ? "" : step.getRowDistribution().getDescription() ) );
tip.append( Const.CR );
tipImage = GUIResource.getInstance().getImageBalance();
break;
case HOP_INFO_ICON:
StepMeta from = (StepMeta) areaOwner.getParent();
StepMeta to = (StepMeta) areaOwner.getOwner();
tip.append( BaseMessages.getString( PKG, "TransGraph.Hop.Tooltip.HopTypeInfo", to.getName(), from.getName(),
Const.CR ) );
tipImage = GUIResource.getInstance().getImageInfoHop();
break;
case HOP_ERROR_ICON:
from = (StepMeta) areaOwner.getParent();
to = (StepMeta) areaOwner.getOwner();
areaOwner.getOwner();
tip.append( BaseMessages.getString( PKG, "TransGraph.Hop.Tooltip.HopTypeError", from.getName(), to.getName(),
Const.CR ) );
tipImage = GUIResource.getInstance().getImageErrorHop();
break;
case HOP_INFO_STEP_COPIES_ERROR:
from = (StepMeta) areaOwner.getParent();
to = (StepMeta) areaOwner.getOwner();
tip.append( BaseMessages.getString( PKG, "TransGraph.Hop.Tooltip.InfoStepCopies", from.getName(), to
.getName(), Const.CR ) );
tipImage = GUIResource.getInstance().getImageStepError();
break;
case STEP_INPUT_HOP_ICON:
// StepMeta subjectStep = (StepMeta) (areaOwner.getParent());
tip.append( BaseMessages.getString( PKG, "TransGraph.StepInputConnector.Tooltip" ) );
tipImage = GUIResource.getInstance().getImageHopInput();
break;
case STEP_OUTPUT_HOP_ICON:
// subjectStep = (StepMeta) (areaOwner.getParent());
tip.append( BaseMessages.getString( PKG, "TransGraph.StepOutputConnector.Tooltip" ) );
tipImage = GUIResource.getInstance().getImageHopOutput();
break;
case STEP_INFO_HOP_ICON:
// subjectStep = (StepMeta) (areaOwner.getParent());
// StreamInterface stream = (StreamInterface) areaOwner.getOwner();
StepIOMetaInterface ioMeta = (StepIOMetaInterface) areaOwner.getOwner();
tip.append( BaseMessages.getString( PKG, "TransGraph.StepInfoConnector.Tooltip" ) + Const.CR
+ ioMeta.toString() );
tipImage = GUIResource.getInstance().getImageHopOutput();
break;
case STEP_TARGET_HOP_ICON:
StreamInterface stream = (StreamInterface) areaOwner.getOwner();
tip.append( stream.getDescription() );
tipImage = GUIResource.getInstance().getImageHopOutput();
break;
case STEP_ERROR_HOP_ICON:
StepMeta stepMeta = (StepMeta) areaOwner.getParent();
if ( stepMeta.supportsErrorHandling() ) {
tip.append( BaseMessages.getString( PKG, "TransGraph.StepSupportsErrorHandling.Tooltip" ) );
} else {
tip.append( BaseMessages.getString( PKG, "TransGraph.StepDoesNotSupportsErrorHandling.Tooltip" ) );
}
tipImage = GUIResource.getInstance().getImageHopOutput();
break;
case STEP_EDIT_ICON:
tip.append( BaseMessages.getString( PKG, "TransGraph.EditStep.Tooltip" ) );
tipImage = GUIResource.getInstance().getImageEdit();
break;
case STEP_INJECT_ICON:
Object injection = areaOwner.getOwner();
if ( injection != null ) {
tip.append( BaseMessages.getString( PKG, "TransGraph.StepInjectionSupported.Tooltip" ) );
} else {
tip.append( BaseMessages.getString( PKG, "TransGraph.StepInjectionNotSupported.Tooltip" ) );
}
tipImage = GUIResource.getInstance().getImageInject();
break;
case STEP_MENU_ICON:
tip.append( BaseMessages.getString( PKG, "TransGraph.ShowMenu.Tooltip" ) );
tipImage = GUIResource.getInstance().getImageContextMenu();
break;
case STEP_ICON:
StepMeta iconStepMeta = (StepMeta) areaOwner.getOwner();
if ( iconStepMeta.isDeprecated() ) { // only need tooltip if step is deprecated
tip.append( BaseMessages.getString( PKG, "TransGraph.DeprecatedStep.Tooltip.Title" ) ).append( Const.CR );
String tipNext = BaseMessages.getString( PKG, "TransGraph.DeprecatedStep.Tooltip.Message1",
iconStepMeta.getName() );
int length = tipNext.length() + 5;
for ( int i = 0; i < length; i++ ) {
tip.append( "-" );
}
tip.append( Const.CR ).append( tipNext ).append( Const.CR );
tip.append( BaseMessages.getString( PKG, "TransGraph.DeprecatedStep.Tooltip.Message2" ) );
if ( !Utils.isEmpty( iconStepMeta.getSuggestion() )
&& !( iconStepMeta.getSuggestion().startsWith( "!" ) && iconStepMeta.getSuggestion().endsWith( "!" ) ) ) {
tip.append( " " );
tip.append( BaseMessages.getString( PKG, "TransGraph.DeprecatedStep.Tooltip.Message3",
iconStepMeta.getSuggestion() ) );
}
tipImage = GUIResource.getInstance().getImageDeprecated();
toolTip.setHideDelay( TOOLTIP_HIDE_DELAY_LONG );
}
break;
default:
break;
}
}
if ( hi != null && tip.length() == 0 ) { // We clicked on a HOP!
// Set the tooltip for the hop:
tip.append( Const.CR ).append( BaseMessages.getString( PKG, "TransGraph.Dialog.HopInfo" ) ).append(
newTip = hi.toString() ).append( Const.CR );
}
if ( tip.length() == 0 ) {
newTip = null;
} else {
newTip = tip.toString();
}
if ( newTip == null ) {
toolTip.hide();
if ( hi != null ) { // We clicked on a HOP!
// Set the tooltip for the hop:
newTip =
BaseMessages.getString( PKG, "TransGraph.Dialog.HopInfo" )
+ Const.CR
+ BaseMessages.getString( PKG, "TransGraph.Dialog.HopInfo.SourceStep" )
+ " "
+ hi.getFromStep().getName()
+ Const.CR
+ BaseMessages.getString( PKG, "TransGraph.Dialog.HopInfo.TargetStep" )
+ " "
+ hi.getToStep().getName()
+ Const.CR
+ BaseMessages.getString( PKG, "TransGraph.Dialog.HopInfo.Status" )
+ " "
+ ( hi.isEnabled() ? BaseMessages.getString( PKG, "TransGraph.Dialog.HopInfo.Enable" ) : BaseMessages
.getString( PKG, "TransGraph.Dialog.HopInfo.Disable" ) );
toolTip.setText( newTip );
if ( hi.isEnabled() ) {
toolTip.setImage( GUIResource.getInstance().getImageHop() );
} else {
toolTip.setImage( GUIResource.getInstance().getImageDisabledHop() );
}
toolTip.show( new org.eclipse.swt.graphics.Point( screenX, screenY ) );
} else {
newTip = null;
}
} else if ( !newTip.equalsIgnoreCase( getToolTipText() ) ) {
Image tooltipImage = null;
if ( tipImage != null ) {
tooltipImage = tipImage;
} else {
tooltipImage = GUIResource.getInstance().getImageSpoonLow();
}
showTooltip( newTip, tooltipImage, screenX, screenY );
}
if ( areaOwner != null && areaOwner.getExtensionAreaType() != null ) {
try {
TransPainterFlyoutTooltipExtension extension =
new TransPainterFlyoutTooltipExtension( areaOwner, this, new Point( screenX, screenY ) );
ExtensionPointHandler.callExtensionPoint(
LogChannel.GENERAL, KettleExtensionPoint.TransPainterFlyoutTooltip.id, extension );
} catch ( Exception e ) {
LogChannel.GENERAL.logError( "Error calling extension point(s) for the transformation painter step", e );
}
}
return subject;
}
public void showTooltip( String label, Image image, int screenX, int screenY ) {
toolTip.setImage( image );
toolTip.setText( label );
toolTip.hide();
toolTip.show( new org.eclipse.swt.graphics.Point( screenX, screenY ) );
}
public AreaOwner getVisibleAreaOwner( int x, int y ) {
for ( int i = areaOwners.size() - 1; i >= 0; i-- ) {
AreaOwner areaOwner = areaOwners.get( i );
if ( areaOwner.contains( x, y ) ) {
return areaOwner;
}
}
return null;
}
public void delSelected( StepMeta stMeta ) {
List<StepMeta> selection = transMeta.getSelectedSteps();
if ( selection.size() == 0 ) {
spoon.delStep( transMeta, stMeta );
return;
}
if ( currentStep != null && selection.contains( currentStep ) ) {
currentStep = null;
transPreviewDelegate.setSelectedStep( currentStep );
transPreviewDelegate.refreshView();
for ( StepSelectionListener listener : currentStepListeners ) {
listener.onUpdateSelection( currentStep );
}
}
StepMeta[] steps = selection.toArray( new StepMeta[ selection.size() ] );
spoon.delSteps( transMeta, steps );
}
public void editDescription( StepMeta stepMeta ) {
String title = BaseMessages.getString( PKG, "TransGraph.Dialog.StepDescription.Title" );
String message = BaseMessages.getString( PKG, "TransGraph.Dialog.StepDescription.Message" );
EnterTextDialog dd = new EnterTextDialog( shell, title, message, stepMeta.getDescription() );
String d = dd.open();
if ( d != null ) {
stepMeta.setDescription( d );
stepMeta.setChanged();
spoon.setShellText();
}
}
/**
* Display the input- or outputfields for a step.
*
* @param stepMeta The step (it's metadata) to query
* @param before set to true if you want to have the fields going INTO the step, false if you want to see all the
* fields that exit the step.
*/
private void inputOutputFields( StepMeta stepMeta, boolean before ) {
spoon.refreshGraph();
transMeta.setRepository( spoon.rep );
SearchFieldsProgressDialog op = new SearchFieldsProgressDialog( transMeta, stepMeta, before );
boolean alreadyThrownError = false;
try {
final ProgressMonitorDialog pmd = new ProgressMonitorDialog( shell );
// Run something in the background to cancel active database queries, forecably if needed!
Runnable run = new Runnable() {
@Override
public void run() {
IProgressMonitor monitor = pmd.getProgressMonitor();
while ( pmd.getShell() == null || ( !pmd.getShell().isDisposed() && !monitor.isCanceled() ) ) {
try {
Thread.sleep( 250 );
} catch ( InterruptedException e ) {
// Ignore
}
}
if ( monitor.isCanceled() ) { // Disconnect and see what happens!
try {
transMeta.cancelQueries();
} catch ( Exception e ) {
// Ignore
}
}
}
};
// Dump the cancel looker in the background!
new Thread( run ).start();
pmd.run( true, true, op );
} catch ( InvocationTargetException e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "TransGraph.Dialog.GettingFields.Title" ), BaseMessages
.getString( PKG, "TransGraph.Dialog.GettingFields.Message" ), e );
alreadyThrownError = true;
} catch ( InterruptedException e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "TransGraph.Dialog.GettingFields.Title" ), BaseMessages
.getString( PKG, "TransGraph.Dialog.GettingFields.Message" ), e );
alreadyThrownError = true;
}
RowMetaInterface fields = op.getFields();
if ( fields != null && fields.size() > 0 ) {
StepFieldsDialog sfd = new StepFieldsDialog( shell, transMeta, SWT.NONE, stepMeta.getName(), fields );
String sn = (String) sfd.open();
if ( sn != null ) {
StepMeta esi = transMeta.findStep( sn );
if ( esi != null ) {
editStep( esi );
}
}
} else {
if ( !alreadyThrownError ) {
modalMessageDialog( getString( "TransGraph.Dialog.CouldntFindFields.Title" ),
getString( "TransGraph.Dialog.CouldntFindFields.Message" ), SWT.OK | SWT.ICON_INFORMATION );
}
}
}
public void paintControl( PaintEvent e ) {
Point area = getArea();
if ( area.x == 0 || area.y == 0 ) {
return; // nothing to do!
}
Display disp = shell.getDisplay();
Image img = getTransformationImage( disp, area.x, area.y, magnification );
e.gc.drawImage( img, 0, 0 );
if ( transMeta.nrSteps() == 0 ) {
e.gc.setForeground( GUIResource.getInstance().getColorCrystalTextPentaho() );
e.gc.setFont( GUIResource.getInstance().getFontMedium() );
Image pentahoImage = GUIResource.getInstance().getImageTransCanvas();
int leftPosition = ( area.x - pentahoImage.getBounds().width ) / 2;
int topPosition = ( area.y - pentahoImage.getBounds().height ) / 2;
e.gc.drawImage( pentahoImage, leftPosition, topPosition );
}
img.dispose();
// spoon.setShellText();
}
public Image getTransformationImage( Device device, int x, int y, float magnificationFactor ) {
GCInterface gc = new SWTGC( device, new Point( x, y ), iconsize );
int gridSize =
PropsUI.getInstance().isShowCanvasGridEnabled() ? PropsUI.getInstance().getCanvasGridSize() : 1;
TransPainter transPainter =
new TransPainter( gc, transMeta, new Point( x, y ), new SwtScrollBar( hori ), new SwtScrollBar( vert ),
candidate, drop_candidate, selectionRegion, areaOwners, mouseOverSteps,
PropsUI.getInstance().getIconSize(), PropsUI.getInstance().getLineWidth(), gridSize,
PropsUI.getInstance().getShadowSize(), PropsUI.getInstance()
.isAntiAliasingEnabled(), PropsUI.getInstance().getNoteFont().getName(), PropsUI.getInstance()
.getNoteFont().getHeight(), trans, PropsUI.getInstance().isIndicateSlowTransStepsEnabled() );
transPainter.setMagnification( magnificationFactor );
transPainter.setStepLogMap( stepLogMap );
transPainter.setStartHopStep( startHopStep );
transPainter.setEndHopLocation( endHopLocation );
transPainter.setNoInputStep( noInputStep );
transPainter.setEndHopStep( endHopStep );
transPainter.setCandidateHopType( candidateHopType );
transPainter.setStartErrorHopStep( startErrorHopStep );
transPainter.setShowTargetStreamsStep( showTargetStreamsStep );
transPainter.buildTransformationImage();
Image img = (Image) gc.getImage();
gc.dispose();
return img;
}
@Override
protected Point getOffset() {
Point area = getArea();
Point max = transMeta.getMaximum();
Point thumb = getThumb( area, max );
return getOffset( thumb, area );
}
private void editStep( StepMeta stepMeta ) {
spoon.editStep( transMeta, stepMeta );
}
private void editNote( NotePadMeta ni ) {
NotePadMeta before = (NotePadMeta) ni.clone();
String title = BaseMessages.getString( PKG, "TransGraph.Dialog.EditNote.Title" );
NotePadDialog dd = new NotePadDialog( transMeta, shell, title, ni );
NotePadMeta n = dd.open();
if ( n != null ) {
ni.setChanged();
ni.setNote( n.getNote() );
ni.setFontName( n.getFontName() );
ni.setFontSize( n.getFontSize() );
ni.setFontBold( n.isFontBold() );
ni.setFontItalic( n.isFontItalic() );
// font color
ni.setFontColorRed( n.getFontColorRed() );
ni.setFontColorGreen( n.getFontColorGreen() );
ni.setFontColorBlue( n.getFontColorBlue() );
// background color
ni.setBackGroundColorRed( n.getBackGroundColorRed() );
ni.setBackGroundColorGreen( n.getBackGroundColorGreen() );
ni.setBackGroundColorBlue( n.getBackGroundColorBlue() );
// border color
ni.setBorderColorRed( n.getBorderColorRed() );
ni.setBorderColorGreen( n.getBorderColorGreen() );
ni.setBorderColorBlue( n.getBorderColorBlue() );
ni.setDrawShadow( n.isDrawShadow() );
ni.width = ConstUI.NOTE_MIN_SIZE;
ni.height = ConstUI.NOTE_MIN_SIZE;
NotePadMeta after = (NotePadMeta) ni.clone();
spoon.addUndoChange( transMeta, new NotePadMeta[] { before }, new NotePadMeta[] { after }, new int[] { transMeta
.indexOfNote( ni ) } );
spoon.refreshGraph();
}
}
private void editHop( TransHopMeta transHopMeta ) {
String name = transHopMeta.toString();
if ( log.isDebug() ) {
log.logDebug( BaseMessages.getString( PKG, "TransGraph.Logging.EditingHop" ) + name );
}
spoon.editHop( transMeta, transHopMeta );
}
private void newHop() {
List<StepMeta> selection = transMeta.getSelectedSteps();
if ( selection.size() == 2 ) {
StepMeta fr = selection.get( 0 );
StepMeta to = selection.get( 1 );
spoon.newHop( transMeta, fr, to );
}
}
private boolean pointOnLine( int x, int y, int[] line ) {
int dx, dy;
int pm = HOP_SEL_MARGIN / 2;
boolean retval = false;
for ( dx = -pm; dx <= pm && !retval; dx++ ) {
for ( dy = -pm; dy <= pm && !retval; dy++ ) {
retval = pointOnThinLine( x + dx, y + dy, line );
}
}
return retval;
}
private boolean pointOnThinLine( int x, int y, int[] line ) {
int x1 = line[ 0 ];
int y1 = line[ 1 ];
int x2 = line[ 2 ];
int y2 = line[ 3 ];
// Not in the square formed by these 2 points: ignore!
// CHECKSTYLE:LineLength:OFF
if ( !( ( ( x >= x1 && x <= x2 ) || ( x >= x2 && x <= x1 ) ) && ( ( y >= y1 && y <= y2 ) || ( y >= y2
&& y <= y1 ) ) ) ) {
return false;
}
double angle_line = Math.atan2( y2 - y1, x2 - x1 ) + Math.PI;
double angle_point = Math.atan2( y - y1, x - x1 ) + Math.PI;
// Same angle, or close enough?
if ( angle_point >= angle_line - 0.01 && angle_point <= angle_line + 0.01 ) {
return true;
}
return false;
}
private SnapAllignDistribute createSnapAllignDistribute() {
List<StepMeta> selection = transMeta.getSelectedSteps();
int[] indices = transMeta.getStepIndexes( selection );
return new SnapAllignDistribute( transMeta, selection, indices, spoon, this );
}
public void snaptogrid() {
snaptogrid( ConstUI.GRID_SIZE );
}
private void snaptogrid( int size ) {
createSnapAllignDistribute().snaptogrid( size );
}
public void allignleft() {
createSnapAllignDistribute().allignleft();
}
public void allignright() {
createSnapAllignDistribute().allignright();
}
public void alligntop() {
createSnapAllignDistribute().alligntop();
}
public void allignbottom() {
createSnapAllignDistribute().allignbottom();
}
public void distributehorizontal() {
createSnapAllignDistribute().distributehorizontal();
}
public void distributevertical() {
createSnapAllignDistribute().distributevertical();
}
private void detach( StepMeta stepMeta ) {
for ( int i = transMeta.nrTransHops() - 1; i >= 0; i-- ) {
TransHopMeta hop = transMeta.getTransHop( i );
if ( stepMeta.equals( hop.getFromStep() ) || stepMeta.equals( hop.getToStep() ) ) {
// Step is connected with a hop, remove this hop.
//
spoon.addUndoNew( transMeta, new TransHopMeta[] { hop }, new int[] { i } );
transMeta.removeTransHop( i );
}
}
/*
* TransHopMeta hfrom = transMeta.findTransHopTo(stepMeta); TransHopMeta hto = transMeta.findTransHopFrom(stepMeta);
*
* if (hfrom != null && hto != null) { if (transMeta.findTransHop(hfrom.getFromStep(), hto.getToStep()) == null) {
* TransHopMeta hnew = new TransHopMeta(hfrom.getFromStep(), hto.getToStep()); transMeta.addTransHop(hnew);
* spoon.addUndoNew(transMeta, new TransHopMeta[] { hnew }, new int[] { transMeta.indexOfTransHop(hnew) });
* spoon.refreshTree(); } } if (hfrom != null) { int fromidx = transMeta.indexOfTransHop(hfrom); if (fromidx >= 0) {
* transMeta.removeTransHop(fromidx); spoon.refreshTree(); } } if (hto != null) { int toidx =
* transMeta.indexOfTransHop(hto); if (toidx >= 0) { transMeta.removeTransHop(toidx); spoon.refreshTree(); } }
*/
spoon.refreshTree();
redraw();
}
// Preview the selected steps...
public void preview() {
spoon.previewTransformation();
}
public void newProps() {
iconsize = spoon.props.getIconSize();
}
@Override
public EngineMetaInterface getMeta() {
return transMeta;
}
/**
* @param transMeta the transMeta to set
* @return the transMeta / public TransMeta getTransMeta() { return transMeta; }
* <p/>
* /**
*/
public void setTransMeta( TransMeta transMeta ) {
this.transMeta = transMeta;
}
// Change of step, connection, hop or note...
public void addUndoPosition( Object[] obj, int[] pos, Point[] prev, Point[] curr ) {
addUndoPosition( obj, pos, prev, curr, false );
}
// Change of step, connection, hop or note...
public void addUndoPosition( Object[] obj, int[] pos, Point[] prev, Point[] curr, boolean nextAlso ) {
// It's better to store the indexes of the objects, not the objects itself!
transMeta.addUndo( obj, null, pos, prev, curr, TransMeta.TYPE_UNDO_POSITION, nextAlso );
spoon.setUndoMenu( transMeta );
}
@Override
public boolean applyChanges() throws KettleException {
return spoon.saveToFile( transMeta );
}
@Override
public boolean canBeClosed() {
return !transMeta.hasChanged();
}
@Override
public TransMeta getManagedObject() {
return transMeta;
}
@Override
public boolean hasContentChanged() {
return transMeta.hasChanged();
}
public List<CheckResultInterface> getRemarks() {
return remarks;
}
public void setRemarks( List<CheckResultInterface> remarks ) {
this.remarks = remarks;
}
public List<DatabaseImpact> getImpact() {
return impact;
}
public void setImpact( List<DatabaseImpact> impact ) {
this.impact = impact;
}
public boolean isImpactFinished() {
return impactFinished;
}
public void setImpactFinished( boolean impactHasRun ) {
this.impactFinished = impactHasRun;
}
/**
* @return the lastMove
*/
public Point getLastMove() {
return lastMove;
}
public static boolean editProperties( TransMeta transMeta, Spoon spoon, Repository rep,
boolean allowDirectoryChange ) {
return editProperties( transMeta, spoon, rep, allowDirectoryChange, null );
}
public static boolean editProperties( TransMeta transMeta, Spoon spoon, Repository rep, boolean allowDirectoryChange,
TransDialog.Tabs currentTab ) {
if ( transMeta == null ) {
return false;
}
TransDialog tid = new TransDialog( spoon.getShell(), SWT.NONE, transMeta, rep, currentTab );
tid.setDirectoryChangeAllowed( allowDirectoryChange );
TransMeta ti = tid.open();
// Load shared objects
//
if ( tid.isSharedObjectsFileChanged() ) {
try {
SharedObjects sharedObjects =
rep != null ? rep.readTransSharedObjects( transMeta ) : transMeta.readSharedObjects();
spoon.sharedObjectsFileMap.put( sharedObjects.getFilename(), sharedObjects );
} catch ( KettleException e ) {
// CHECKSTYLE:LineLength:OFF
new ErrorDialog( spoon.getShell(),
BaseMessages.getString( PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Title" ), BaseMessages.getString( PKG,
"Spoon.Dialog.ErrorReadingSharedObjects.Message", spoon.makeTabName( transMeta, true ) ), e );
}
// If we added properties, add them to the variables too, so that they appear in the CTRL-SPACE variable
// completion.
//
spoon.setParametersAsVariablesInUI( transMeta, transMeta );
spoon.refreshTree();
spoon.delegates.tabs.renameTabs(); // cheap operation, might as will do it anyway
}
spoon.setShellText();
return ti != null;
}
public void openFile() {
spoon.openFile();
}
public void saveFile() throws KettleException {
spoon.saveFile();
}
public void saveFileAs() throws KettleException {
spoon.saveFileAs();
}
public void saveXMLFileToVfs() {
spoon.saveXMLFileToVfs();
}
public void printFile() {
spoon.printFile();
}
public void runTransformation() {
spoon.runFile();
}
public void runOptionsTransformation() {
spoon.runOptionsFile();
}
public void pauseTransformation() {
pauseResume();
}
public void stopTransformation() {
stop();
}
public void previewFile() {
spoon.previewFile();
}
public void debugFile() {
spoon.debugFile();
}
public void transReplay() {
spoon.replayTransformation();
}
public void checkTrans() {
spoon.checkTrans();
}
public void analyseImpact() {
spoon.analyseImpact();
}
public void getSQL() {
spoon.getSQL();
}
public void exploreDatabase() {
spoon.exploreDatabase();
}
public boolean isExecutionResultsPaneVisible() {
return extraViewComposite != null && !extraViewComposite.isDisposed();
}
public void showExecutionResults() {
if ( isExecutionResultsPaneVisible() ) {
disposeExtraView();
} else {
addAllTabs();
}
}
public void browseVersionHistory() {
try {
if ( spoon.rep.exists( transMeta.getName(), transMeta.getRepositoryDirectory(),
RepositoryObjectType.TRANSFORMATION ) ) {
RepositoryRevisionBrowserDialogInterface dialog =
RepositoryExplorerDialog.getVersionBrowserDialog( shell, spoon.rep, transMeta );
String versionLabel = dialog.open();
if ( versionLabel != null ) {
spoon.loadObjectFromRepository( transMeta.getName(), transMeta.getRepositoryElementType(), transMeta
.getRepositoryDirectory(), versionLabel );
}
} else {
modalMessageDialog( getString( "TransGraph.Sorry" ),
getString( "TransGraph.VersionBrowser.CantFindInRepo" ), SWT.CLOSE | SWT.ICON_ERROR );
}
} catch ( Exception e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "TransGraph.VersionBrowserException.Title" ), BaseMessages
.getString( PKG, "TransGraph.VersionBrowserException.Message" ), e );
}
}
/**
* If the extra tab view at the bottom is empty, we close it.
*/
public void checkEmptyExtraView() {
if ( extraViewTabFolder.getItemCount() == 0 ) {
disposeExtraView();
}
}
private void disposeExtraView() {
extraViewComposite.dispose();
sashForm.layout();
sashForm.setWeights( new int[] { 100, } );
XulToolbarbutton button = (XulToolbarbutton) toolbar.getElementById( "trans-show-results" );
button.setTooltiptext( BaseMessages.getString( PKG, "Spoon.Tooltip.ShowExecutionResults" ) );
ToolItem toolItem = (ToolItem) button.getManagedObject();
toolItem.setImage( GUIResource.getInstance().getImageShowResults() );
}
private void minMaxExtraView() {
// What is the state?
//
boolean maximized = sashForm.getMaximizedControl() != null;
if ( maximized ) {
// Minimize
//
sashForm.setMaximizedControl( null );
minMaxButton.setImage( GUIResource.getInstance().getImageMaximizePanel() );
minMaxButton
.setToolTipText( BaseMessages.getString( PKG, "TransGraph.ExecutionResultsPanel.MaxButton.Tooltip" ) );
} else {
// Maximize
//
sashForm.setMaximizedControl( extraViewComposite );
minMaxButton.setImage( GUIResource.getInstance().getImageMinimizePanel() );
minMaxButton
.setToolTipText( BaseMessages.getString( PKG, "TransGraph.ExecutionResultsPanel.MinButton.Tooltip" ) );
}
}
/**
* @return the toolbar
*/
public XulToolbar getToolbar() {
return toolbar;
}
/**
* @param toolbar the toolbar to set
*/
public void setToolbar( XulToolbar toolbar ) {
this.toolbar = toolbar;
}
private Label closeButton;
private Label minMaxButton;
/**
* Add an extra view to the main composite SashForm
*/
public void addExtraView() {
extraViewComposite = new Composite( sashForm, SWT.NONE );
FormLayout extraCompositeFormLayout = new FormLayout();
extraCompositeFormLayout.marginWidth = 2;
extraCompositeFormLayout.marginHeight = 2;
extraViewComposite.setLayout( extraCompositeFormLayout );
// Put a close and max button to the upper right corner...
//
closeButton = new Label( extraViewComposite, SWT.NONE );
closeButton.setImage( GUIResource.getInstance().getImageClosePanel() );
closeButton.setToolTipText( BaseMessages.getString( PKG, "TransGraph.ExecutionResultsPanel.CloseButton.Tooltip" ) );
FormData fdClose = new FormData();
fdClose.right = new FormAttachment( 100, 0 );
fdClose.top = new FormAttachment( 0, 0 );
closeButton.setLayoutData( fdClose );
closeButton.addMouseListener( new MouseAdapter() {
@Override
public void mouseDown( MouseEvent e ) {
disposeExtraView();
}
} );
minMaxButton = new Label( extraViewComposite, SWT.NONE );
minMaxButton.setImage( GUIResource.getInstance().getImageMaximizePanel() );
minMaxButton.setToolTipText( BaseMessages.getString( PKG, "TransGraph.ExecutionResultsPanel.MaxButton.Tooltip" ) );
FormData fdMinMax = new FormData();
fdMinMax.right = new FormAttachment( closeButton, -Const.MARGIN );
fdMinMax.top = new FormAttachment( 0, 0 );
minMaxButton.setLayoutData( fdMinMax );
minMaxButton.addMouseListener( new MouseAdapter() {
@Override
public void mouseDown( MouseEvent e ) {
minMaxExtraView();
}
} );
// Add a label at the top: Results
//
Label wResultsLabel = new Label( extraViewComposite, SWT.LEFT );
wResultsLabel.setFont( GUIResource.getInstance().getFontMediumBold() );
wResultsLabel.setBackground( GUIResource.getInstance().getColorWhite() );
wResultsLabel.setText( BaseMessages.getString( PKG, "TransLog.ResultsPanel.NameLabel" ) );
FormData fdResultsLabel = new FormData();
fdResultsLabel.left = new FormAttachment( 0, 0 );
fdResultsLabel.right = new FormAttachment( minMaxButton, -Const.MARGIN );
fdResultsLabel.top = new FormAttachment( 0, 0 );
wResultsLabel.setLayoutData( fdResultsLabel );
// Add a tab folder ...
//
extraViewTabFolder = new CTabFolder( extraViewComposite, SWT.MULTI );
spoon.props.setLook( extraViewTabFolder, Props.WIDGET_STYLE_TAB );
extraViewTabFolder.addMouseListener( new MouseAdapter() {
@Override
public void mouseDoubleClick( MouseEvent arg0 ) {
if ( sashForm.getMaximizedControl() == null ) {
sashForm.setMaximizedControl( extraViewComposite );
} else {
sashForm.setMaximizedControl( null );
}
}
} );
FormData fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment( 0, 0 );
fdTabFolder.right = new FormAttachment( 100, 0 );
fdTabFolder.top = new FormAttachment( wResultsLabel, Const.MARGIN );
fdTabFolder.bottom = new FormAttachment( 100, 0 );
extraViewTabFolder.setLayoutData( fdTabFolder );
sashForm.setWeights( new int[] { 60, 40, } );
}
/**
* @deprecated Deprecated as of 8.0. Seems unused; will be to remove in 8.1 (ccaspanello)
*/
@Deprecated
public void checkErrors() {
if ( trans != null ) {
if ( !trans.isFinished() ) {
if ( trans.getErrors() != 0 ) {
trans.killAll();
}
}
}
}
public synchronized void start( TransExecutionConfiguration executionConfiguration ) throws KettleException {
// Auto save feature...
handleTransMetaChanges( transMeta );
if ( ( ( transMeta.getName() != null && transMeta.getObjectId() != null && spoon.rep != null ) || // Repository
// available &
// name / id set
( transMeta.getFilename() != null && spoon.rep == null ) // No repository & filename set
)
&& !transMeta.hasChanged() // Didn't change
) {
if ( trans == null || !running ) {
try {
// Set the requested logging level..
//
DefaultLogLevel.setLogLevel( executionConfiguration.getLogLevel() );
transMeta.injectVariables( executionConfiguration.getVariables() );
// Set the named parameters
Map<String, String> paramMap = executionConfiguration.getParams();
Set<String> keys = paramMap.keySet();
for ( String key : keys ) {
transMeta.setParameterValue( key, Const.NVL( paramMap.get( key ), "" ) );
}
transMeta.activateParameters();
// Do we need to clear the log before running?
//
if ( executionConfiguration.isClearingLog() ) {
transLogDelegate.clearLog();
}
// Also make sure to clear the log entries in the central log store & registry
//
if ( trans != null ) {
KettleLogStore.discardLines( trans.getLogChannelId(), true );
}
// Important: even though transMeta is passed to the Trans constructor, it is not the same object as is in
// memory
// To be able to completely test this, we need to run it as we would normally do in pan
//
trans = this.createLegacyTrans();
trans.setRepository( spoon.getRepository() );
trans.setMetaStore( spoon.getMetaStore() );
String spoonLogObjectId = UUID.randomUUID().toString();
SimpleLoggingObject spoonLoggingObject = new SimpleLoggingObject( "SPOON", LoggingObjectType.SPOON, null );
spoonLoggingObject.setContainerObjectId( spoonLogObjectId );
spoonLoggingObject.setLogLevel( executionConfiguration.getLogLevel() );
trans.setParent( spoonLoggingObject );
trans.setLogLevel( executionConfiguration.getLogLevel() );
trans.setReplayDate( executionConfiguration.getReplayDate() );
trans.setRepository( executionConfiguration.getRepository() );
trans.setMonitored( true );
log.logBasic( BaseMessages.getString( PKG, "TransLog.Log.TransformationOpened" ) );
} catch ( KettleException e ) {
trans = null;
new ErrorDialog( shell, BaseMessages.getString( PKG, "TransLog.Dialog.ErrorOpeningTransformation.Title" ),
BaseMessages.getString( PKG, "TransLog.Dialog.ErrorOpeningTransformation.Message" ), e );
}
if ( trans != null ) {
Map<String, String> arguments = executionConfiguration.getArguments();
final String[] args;
if ( arguments != null ) {
args = convertArguments( arguments );
} else {
args = null;
}
log.logMinimal( BaseMessages.getString( PKG, "TransLog.Log.LaunchingTransformation" )
+ trans.getTransMeta().getName() + "]..." );
trans.setSafeModeEnabled( executionConfiguration.isSafeModeEnabled() );
trans.setGatheringMetrics( executionConfiguration.isGatheringMetrics() );
// Launch the step preparation in a different thread.
// That way Spoon doesn't block anymore and that way we can follow the progress of the initialization
//
final Thread parentThread = Thread.currentThread();
shell.getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
addAllTabs();
prepareTrans( parentThread, args );
}
} );
log.logMinimal( BaseMessages.getString( PKG, "TransLog.Log.StartedExecutionOfTransformation" ) );
setControlStates();
}
} else {
modalMessageDialog( getString( "TransLog.Dialog.DoNoStartTransformationTwice.Title" ),
getString( "TransLog.Dialog.DoNoStartTransformationTwice.Message" ), SWT.OK | SWT.ICON_WARNING );
}
} else {
if ( transMeta.hasChanged() ) {
showSaveFileMessage();
} else if ( spoon.rep != null && transMeta.getName() == null ) {
modalMessageDialog( getString( "TransLog.Dialog.GiveTransformationANameBeforeRunning.Title" ),
getString( "TransLog.Dialog.GiveTransformationANameBeforeRunning.Message" ), SWT.OK | SWT.ICON_WARNING );
} else {
modalMessageDialog( getString( "TransLog.Dialog.SaveTransformationBeforeRunning2.Title" ),
getString( "TransLog.Dialog.SaveTransformationBeforeRunning2.Message" ), SWT.OK | SWT.ICON_WARNING );
}
}
}
public void showSaveFileMessage() {
modalMessageDialog( getString( "TransLog.Dialog.SaveTransformationBeforeRunning.Title" ),
getString( "TransLog.Dialog.SaveTransformationBeforeRunning.Message" ), SWT.OK | SWT.ICON_WARNING );
}
public void addAllTabs() {
CTabItem tabItemSelection = null;
if ( extraViewTabFolder != null && !extraViewTabFolder.isDisposed() ) {
tabItemSelection = extraViewTabFolder.getSelection();
}
transHistoryDelegate.addTransHistory();
transLogDelegate.addTransLog();
transGridDelegate.addTransGrid();
transPerfDelegate.addTransPerf();
transMetricsDelegate.addTransMetrics();
transPreviewDelegate.addTransPreview();
List<SpoonUiExtenderPluginInterface> relevantExtenders =
SpoonUiExtenderPluginType.getInstance().getRelevantExtenders( TransGraph.class, LOAD_TAB );
for ( SpoonUiExtenderPluginInterface relevantExtender : relevantExtenders ) {
relevantExtender.uiEvent( this, LOAD_TAB );
}
if ( tabItemSelection != null ) {
extraViewTabFolder.setSelection( tabItemSelection );
} else {
extraViewTabFolder.setSelection( transGridDelegate.getTransGridTab() );
}
XulToolbarbutton button = (XulToolbarbutton) toolbar.getElementById( "trans-show-results" );
button.setTooltiptext( BaseMessages.getString( PKG, "Spoon.Tooltip.HideExecutionResults" ) );
ToolItem toolItem = (ToolItem) button.getManagedObject();
toolItem.setImage( GUIResource.getInstance().getImageHideResults() );
}
public synchronized void debug( TransExecutionConfiguration executionConfiguration, TransDebugMeta transDebugMeta ) {
if ( !running ) {
try {
this.lastTransDebugMeta = transDebugMeta;
log.setLogLevel( executionConfiguration.getLogLevel() );
if ( log.isDetailed() ) {
log.logDetailed( BaseMessages.getString( PKG, "TransLog.Log.DoPreview" ) );
}
String[] args = null;
Map<String, String> arguments = executionConfiguration.getArguments();
if ( arguments != null ) {
args = convertArguments( arguments );
}
transMeta.injectVariables( executionConfiguration.getVariables() );
// Set the named parameters
Map<String, String> paramMap = executionConfiguration.getParams();
Set<String> keys = paramMap.keySet();
for ( String key : keys ) {
transMeta.setParameterValue( key, Const.NVL( paramMap.get( key ), "" ) );
}
transMeta.activateParameters();
// Do we need to clear the log before running?
//
if ( executionConfiguration.isClearingLog() ) {
transLogDelegate.clearLog();
}
// Do we have a previous execution to clean up in the logging registry?
//
if ( trans != null ) {
KettleLogStore.discardLines( trans.getLogChannelId(), false );
LoggingRegistry.getInstance().removeIncludingChildren( trans.getLogChannelId() );
}
// Create a new transformation to execution
//
trans = new Trans( transMeta );
trans.setSafeModeEnabled( executionConfiguration.isSafeModeEnabled() );
trans.setPreview( true );
trans.setGatheringMetrics( executionConfiguration.isGatheringMetrics() );
trans.setMetaStore( spoon.getMetaStore() );
trans.prepareExecution( args );
trans.setRepository( spoon.rep );
List<SpoonUiExtenderPluginInterface> relevantExtenders =
SpoonUiExtenderPluginType.getInstance().getRelevantExtenders( TransDebugMetaWrapper.class, PREVIEW_TRANS );
TransDebugMetaWrapper transDebugMetaWrapper = new TransDebugMetaWrapper( trans, transDebugMeta );
for ( SpoonUiExtenderPluginInterface relevantExtender : relevantExtenders ) {
relevantExtender.uiEvent( transDebugMetaWrapper, PREVIEW_TRANS );
}
// Add the row listeners to the allocated threads
//
transDebugMeta.addRowListenersToTransformation( trans );
// What method should we call back when a break-point is hit?
transDebugMeta.addBreakPointListers( new BreakPointListener() {
@Override
public void breakPointHit( TransDebugMeta transDebugMeta, StepDebugMeta stepDebugMeta,
RowMetaInterface rowBufferMeta, List<Object[]> rowBuffer ) {
showPreview( transDebugMeta, stepDebugMeta, rowBufferMeta, rowBuffer );
}
} );
// Do we capture data?
//
if ( transPreviewDelegate.isActive() ) {
transPreviewDelegate.capturePreviewData( trans, transMeta.getSteps() );
}
// Start the threads for the steps...
//
startThreads();
debug = true;
// Show the execution results view...
//
shell.getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
addAllTabs();
}
} );
} catch ( Exception e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "TransLog.Dialog.UnexpectedErrorDuringPreview.Title" ),
BaseMessages.getString( PKG, "TransLog.Dialog.UnexpectedErrorDuringPreview.Message" ), e );
}
} else {
modalMessageDialog( getString( "TransLog.Dialog.DoNoPreviewWhileRunning.Title" ),
getString( "TransLog.Dialog.DoNoPreviewWhileRunning.Message" ), SWT.OK | SWT.ICON_WARNING );
}
checkErrorVisuals();
}
public synchronized void showPreview( final TransDebugMeta transDebugMeta, final StepDebugMeta stepDebugMeta,
final RowMetaInterface rowBufferMeta, final List<Object[]> rowBuffer ) {
shell.getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
if ( isDisposed() ) {
return;
}
spoon.enableMenus();
// The transformation is now paused, indicate this in the log dialog...
//
pausing = true;
setControlStates();
checkErrorVisuals();
PreviewRowsDialog previewRowsDialog =
new PreviewRowsDialog(
shell, transMeta, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.APPLICATION_MODAL | SWT.SHEET,
stepDebugMeta.getStepMeta().getName(), rowBufferMeta, rowBuffer );
previewRowsDialog.setProposingToGetMoreRows( true );
previewRowsDialog.setProposingToStop( true );
previewRowsDialog.open();
if ( previewRowsDialog.isAskingForMoreRows() ) {
// clear the row buffer.
// That way if you click resume, you get the next N rows for the step :-)
//
rowBuffer.clear();
// Resume running: find more rows...
//
pauseResume();
}
if ( previewRowsDialog.isAskingToStop() ) {
// Stop running
//
stop();
}
}
} );
}
private String[] convertArguments( Map<String, String> arguments ) {
String[] argumentNames = arguments.keySet().toArray( new String[ arguments.size() ] );
Arrays.sort( argumentNames );
String[] args = new String[ argumentNames.length ];
for ( int i = 0; i < args.length; i++ ) {
String argumentName = argumentNames[ i ];
args[ i ] = arguments.get( argumentName );
}
return args;
}
public void stop() {
if ( safeStopping ) {
modalMessageDialog( getString( "TransLog.Log.SafeStopAlreadyStarted.Title" ),
getString( "TransLog.Log.SafeStopAlreadyStarted" ), SWT.ICON_ERROR | SWT.OK );
return;
}
if ( ( running && !halting ) ) {
halting = true;
trans.stopAll();
log.logMinimal( BaseMessages.getString( PKG, "TransLog.Log.ProcessingOfTransformationStopped" ) );
running = false;
initialized = false;
halted = false;
halting = false;
setControlStates();
transMeta.setInternalKettleVariables(); // set the original vars back as they may be changed by a mapping
}
}
public void safeStop() {
if ( running && !halting ) {
halting = true;
safeStopping = true;
trans.safeStop();
log.logMinimal( BaseMessages.getString( PKG, "TransLog.Log.TransformationSafeStopped" ) );
initialized = false;
halted = false;
setControlStates();
transMeta.setInternalKettleVariables(); // set the original vars back as they may be changed by a mapping
}
}
public synchronized void pauseResume() {
if ( running ) {
// Get the pause toolbar item
//
if ( !pausing ) {
pausing = true;
trans.pauseRunning();
setControlStates();
} else {
pausing = false;
trans.resumeRunning();
setControlStates();
}
}
}
private boolean controlDisposed( XulToolbarbutton button ) {
if ( button.getManagedObject() instanceof Widget ) {
Widget widget = (Widget) button.getManagedObject();
return widget.isDisposed();
}
return false;
}
@Override
public synchronized void setControlStates() {
if ( isDisposed() || getDisplay().isDisposed() ) {
return;
}
if ( ( (Control) toolbar.getManagedObject() ).isDisposed() ) {
return;
}
getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
boolean operationsNotAllowed = false;
try {
operationsNotAllowed =
RepositorySecurityUI.verifyOperations( shell, spoon.rep, false,
RepositoryOperation.EXECUTE_TRANSFORMATION );
} catch ( KettleRepositoryLostException krle ) {
log.logError( krle.getLocalizedMessage() );
spoon.handleRepositoryLost( krle );
}
// Start/Run button...
//
XulToolbarbutton runButton = (XulToolbarbutton) toolbar.getElementById( "trans-run" );
if ( runButton != null && !controlDisposed( runButton ) && !operationsNotAllowed ) {
if ( runButton.isDisabled() ^ running ) {
runButton.setDisabled( running );
}
}
// Pause button...
//
XulToolbarbutton pauseButton = (XulToolbarbutton) toolbar.getElementById( "trans-pause" );
if ( pauseButton != null && !controlDisposed( pauseButton ) ) {
if ( pauseButton.isDisabled() ^ !running ) {
pauseButton.setDisabled( !running );
pauseButton.setLabel( pausing ? RESUME_TEXT : PAUSE_TEXT );
pauseButton.setTooltiptext( pausing ? BaseMessages.getString( PKG, "Spoon.Tooltip.ResumeTranformation" )
: BaseMessages.getString( PKG, "Spoon.Tooltip.PauseTranformation" ) );
}
}
// Stop button...
//
if ( !stopItem.isDisposed() && !stopItem.isEnabled() ^ !running ) {
stopItem.setEnabled( running );
}
// Debug button...
//
XulToolbarbutton debugButton = (XulToolbarbutton) toolbar.getElementById( "trans-debug" );
if ( debugButton != null && !controlDisposed( debugButton ) && !operationsNotAllowed ) {
if ( debugButton.isDisabled() ^ running ) {
debugButton.setDisabled( running );
}
}
// Preview button...
//
XulToolbarbutton previewButton = (XulToolbarbutton) toolbar.getElementById( "trans-preview" );
if ( previewButton != null && !controlDisposed( previewButton ) && !operationsNotAllowed ) {
if ( previewButton.isDisabled() ^ running ) {
previewButton.setDisabled( running );
}
}
}
} );
}
private synchronized void prepareTrans( final Thread parentThread, final String[] args ) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
trans.setInitialLogBufferStartLine();
trans.prepareExecution( args );
// Do we capture data?
//
if ( transPreviewDelegate.isActive() ) {
transPreviewDelegate.capturePreviewData( trans, transMeta.getSteps() );
}
initialized = true;
} catch ( KettleException e ) {
log.logError( trans.getName() + ": preparing transformation execution failed", e );
checkErrorVisuals();
}
halted = trans.hasHaltedSteps();
if ( trans.isReadyToStart() ) {
checkStartThreads(); // After init, launch the threads.
} else {
initialized = false;
running = false;
checkErrorVisuals();
}
}
};
Thread thread = new Thread( runnable );
thread.start();
}
private void checkStartThreads() {
if ( initialized && !running && trans != null ) {
startThreads();
}
}
private synchronized void startThreads() {
running = true;
try {
// Add a listener to the transformation.
// If the transformation is done, we want to do the end processing, etc.
//
trans.addTransListener( new org.pentaho.di.trans.TransAdapter() {
@Override
public void transFinished( Trans trans ) {
checkTransEnded();
checkErrorVisuals();
stopRedrawTimer();
transMetricsDelegate.resetLastRefreshTime();
transMetricsDelegate.updateGraph();
}
} );
trans.startThreads();
startRedrawTimer();
setControlStates();
} catch ( KettleException e ) {
log.logError( "Error starting step threads", e );
checkErrorVisuals();
stopRedrawTimer();
}
// See if we have to fire off the performance graph updater etc.
//
getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
if ( transPerfDelegate.getTransPerfTab() != null ) {
// If there is a tab open, try to the correct content on there now
//
transPerfDelegate.setupContent();
transPerfDelegate.layoutPerfComposite();
}
}
} );
}
private void startRedrawTimer() {
redrawTimer = new Timer( "TransGraph: redraw timer" );
TimerTask timtask = new TimerTask() {
@Override
public void run() {
if ( !spoon.getDisplay().isDisposed() ) {
spoon.getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
if ( !TransGraph.this.canvas.isDisposed() ) {
TransGraph.this.canvas.redraw();
}
}
} );
}
}
};
redrawTimer.schedule( timtask, 0L, ConstUI.INTERVAL_MS_TRANS_CANVAS_REFRESH );
}
protected void stopRedrawTimer() {
if ( redrawTimer != null ) {
redrawTimer.cancel();
redrawTimer.purge();
redrawTimer = null;
}
}
private void checkTransEnded() {
if ( trans != null ) {
if ( trans.isFinished() && ( running || halted ) ) {
log.logMinimal( BaseMessages.getString( PKG, "TransLog.Log.TransformationHasFinished" ) );
running = false;
initialized = false;
halted = false;
halting = false;
safeStopping = false;
setControlStates();
// OK, also see if we had a debugging session going on.
// If so and we didn't hit a breakpoint yet, display the show
// preview dialog...
//
if ( debug && lastTransDebugMeta != null && lastTransDebugMeta.getTotalNumberOfHits() == 0 ) {
debug = false;
showLastPreviewResults();
}
debug = false;
checkErrorVisuals();
shell.getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
spoon.fireMenuControlers();
redraw();
}
} );
}
}
}
private void checkErrorVisuals() {
if ( trans.getErrors() > 0 ) {
// Get the logging text and filter it out. Store it in the stepLogMap...
//
stepLogMap = new HashMap<>();
shell.getDisplay().syncExec( new Runnable() {
@Override
public void run() {
for ( StepMetaDataCombi combi : trans.getSteps() ) {
if ( combi.step.getErrors() > 0 ) {
String channelId = combi.step.getLogChannel().getLogChannelId();
List<KettleLoggingEvent> eventList =
KettleLogStore.getLogBufferFromTo( channelId, false, 0, KettleLogStore.getLastBufferLineNr() );
StringBuilder logText = new StringBuilder();
for ( KettleLoggingEvent event : eventList ) {
Object message = event.getMessage();
if ( message instanceof LogMessage ) {
LogMessage logMessage = (LogMessage) message;
if ( logMessage.isError() ) {
logText.append( logMessage.getMessage() ).append( Const.CR );
}
}
}
stepLogMap.put( combi.stepMeta, logText.toString() );
}
}
}
} );
} else {
stepLogMap = null;
}
// Redraw the canvas to show the error icons etc.
//
shell.getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
redraw();
}
} );
}
public synchronized void showLastPreviewResults() {
if ( lastTransDebugMeta == null || lastTransDebugMeta.getStepDebugMetaMap().isEmpty() ) {
return;
}
final List<String> stepnames = new ArrayList<>();
final List<RowMetaInterface> rowMetas = new ArrayList<>();
final List<List<Object[]>> rowBuffers = new ArrayList<>();
// Assemble the buffers etc in the old style...
//
for ( StepMeta stepMeta : lastTransDebugMeta.getStepDebugMetaMap().keySet() ) {
StepDebugMeta stepDebugMeta = lastTransDebugMeta.getStepDebugMetaMap().get( stepMeta );
stepnames.add( stepMeta.getName() );
rowMetas.add( stepDebugMeta.getRowBufferMeta() );
rowBuffers.add( stepDebugMeta.getRowBuffer() );
}
getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
EnterPreviewRowsDialog dialog = new EnterPreviewRowsDialog( shell, SWT.NONE, stepnames, rowMetas, rowBuffers );
dialog.open();
}
} );
}
/**
* XUL dummy menu entry
*/
public void openMapping() {
}
/**
* Open the transformation mentioned in the mapping...
*/
public void openMapping( StepMeta stepMeta, int index ) {
try {
Object referencedMeta = null;
Trans subTrans = getActiveSubtransformation( this, stepMeta );
if ( subTrans != null
&& ( stepMeta.getStepMetaInterface().getActiveReferencedObjectDescription() == null || index < 0 ) ) {
TransMeta subTransMeta = subTrans.getTransMeta();
referencedMeta = subTransMeta;
Object[] objectArray = new Object[ 4 ];
objectArray[ 0 ] = stepMeta;
objectArray[ 1 ] = subTransMeta;
ExtensionPointHandler.callExtensionPoint( log, KettleExtensionPoint.OpenMapping.id, objectArray );
} else {
StepMetaInterface meta = stepMeta.getStepMetaInterface();
if ( !Utils.isEmpty( meta.getReferencedObjectDescriptions() ) ) {
referencedMeta = meta.loadReferencedObject( index, spoon.rep, spoon.getMetaStore(), transMeta );
}
}
if ( referencedMeta == null ) {
return;
}
if ( referencedMeta instanceof TransMeta ) {
TransMeta mappingMeta = (TransMeta) referencedMeta;
mappingMeta.clearChanged();
spoon.addTransGraph( mappingMeta );
TransGraph subTransGraph = spoon.getActiveTransGraph();
attachActiveTrans( subTransGraph, this.currentStep );
}
if ( referencedMeta instanceof JobMeta ) {
JobMeta jobMeta = (JobMeta) referencedMeta;
jobMeta.clearChanged();
spoon.addJobGraph( jobMeta );
JobGraph jobGraph = spoon.getActiveJobGraph();
attachActiveJob( jobGraph, this.currentStep );
}
} catch ( Exception e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "TransGraph.Exception.UnableToLoadMapping.Title" ),
BaseMessages.getString( PKG, "TransGraph.Exception.UnableToLoadMapping.Message" ), e );
}
}
/**
* Finds the last active transformation in the running job to the opened transMeta
*
* @param transGraph
* @param stepMeta
*/
private void attachActiveTrans( TransGraph transGraph, StepMeta stepMeta ) {
if ( trans != null && transGraph != null ) {
Trans subTransformation = trans.getActiveSubTransformation( stepMeta.getName() );
transGraph.setTrans( subTransformation );
if ( !transGraph.isExecutionResultsPaneVisible() ) {
transGraph.showExecutionResults();
}
transGraph.setControlStates();
}
}
/**
* Finds the last active transformation in the running job to the opened transMeta
*
* @param transGraph
* @param stepMeta
*/
private Trans getActiveSubtransformation( TransGraph transGraph, StepMeta stepMeta ) {
if ( trans != null && transGraph != null ) {
return trans.getActiveSubTransformation( stepMeta.getName() );
}
return null;
}
/**
* Finds the last active job in the running transformation to the opened jobMeta
*
* @param jobGraph
* @param stepMeta
*/
private void attachActiveJob( JobGraph jobGraph, StepMeta stepMeta ) {
if ( trans != null && jobGraph != null ) {
Job subJob = trans.getActiveSubjobs().get( stepMeta.getName() );
jobGraph.setJob( subJob );
if ( !jobGraph.isExecutionResultsPaneVisible() ) {
jobGraph.showExecutionResults();
}
jobGraph.setControlStates();
}
}
/**
* @return the running
*/
public boolean isRunning() {
return running;
}
/**
* @param running the running to set
*/
public void setRunning( boolean running ) {
this.running = running;
}
/**
* @return the lastTransDebugMeta
*/
public TransDebugMeta getLastTransDebugMeta() {
return lastTransDebugMeta;
}
/**
* @return the halting
*/
public boolean isHalting() {
return halting;
}
/**
* @param halting the halting to set
*/
public void setHalting( boolean halting ) {
this.halting = halting;
}
/**
* @return the stepLogMap
*/
public Map<StepMeta, String> getStepLogMap() {
return stepLogMap;
}
/**
* @param stepLogMap the stepLogMap to set
*/
public void setStepLogMap( Map<StepMeta, String> stepLogMap ) {
this.stepLogMap = stepLogMap;
}
public void dumpLoggingRegistry() {
LoggingRegistry registry = LoggingRegistry.getInstance();
Map<String, LoggingObjectInterface> loggingMap = registry.getMap();
for ( LoggingObjectInterface loggingObject : loggingMap.values() ) {
System.out.println( loggingObject.getLogChannelId() + " - " + loggingObject.getObjectName() + " - "
+ loggingObject.getObjectType() );
}
}
@Override
public HasLogChannelInterface getLogChannelProvider() {
return new HasLogChannelInterface() {
@Override
public LogChannelInterface getLogChannel() {
return getTrans() != null ? getTrans().getLogChannel() : getTransMeta().getLogChannel();
}
};
}
public synchronized void setTrans( Trans trans ) {
this.trans = trans;
if ( trans != null ) {
pausing = trans.isPaused();
initialized = trans.isInitializing();
running = trans.isRunning();
halted = trans.isStopped();
if ( running ) {
trans.addTransListener( new org.pentaho.di.trans.TransAdapter() {
@Override
public void transFinished( Trans trans ) {
checkTransEnded();
checkErrorVisuals();
}
} );
}
}
}
public void sniffInput() {
sniff( true, false, false );
}
public void sniffOutput() {
sniff( false, true, false );
}
public void sniffError() {
sniff( false, false, true );
}
public void sniff( final boolean input, final boolean output, final boolean error ) {
StepMeta stepMeta = getCurrentStep();
if ( stepMeta == null || trans == null ) {
return;
}
final StepInterface runThread = trans.findRunThread( stepMeta.getName() );
if ( runThread != null ) {
List<Object[]> rows = new ArrayList<>();
final PreviewRowsDialog dialog = new PreviewRowsDialog( shell, trans, SWT.NONE, stepMeta.getName(), null, rows );
dialog.setDynamic( true );
// Add a row listener that sends the rows over to the dialog...
//
final RowListener rowListener = new RowListener() {
@Override
public void rowReadEvent( RowMetaInterface rowMeta, Object[] row ) throws KettleStepException {
if ( input ) {
try {
dialog.addDataRow( rowMeta, rowMeta.cloneRow( row ) );
} catch ( KettleValueException e ) {
throw new KettleStepException( e );
}
}
}
@Override
public void rowWrittenEvent( RowMetaInterface rowMeta, Object[] row ) throws KettleStepException {
if ( output ) {
try {
dialog.addDataRow( rowMeta, rowMeta.cloneRow( row ) );
} catch ( KettleValueException e ) {
throw new KettleStepException( e );
}
}
}
@Override
public void errorRowWrittenEvent( RowMetaInterface rowMeta, Object[] row ) throws KettleStepException {
if ( error ) {
try {
dialog.addDataRow( rowMeta, rowMeta.cloneRow( row ) );
} catch ( KettleValueException e ) {
throw new KettleStepException( e );
}
}
}
};
// When the dialog is closed, make sure to remove the listener!
//
dialog.addDialogClosedListener( new DialogClosedListener() {
@Override
public void dialogClosed() {
runThread.removeRowListener( rowListener );
}
} );
// Open the dialog in a separate thread to make sure it doesn't block
//
getDisplay().asyncExec( new Runnable() {
@Override
public void run() {
dialog.open();
}
} );
runThread.addRowListener( rowListener );
}
}
@Override
public String getName() {
return "transgraph";
}
/*
* (non-Javadoc)
*
* @see org.pentaho.ui.xul.impl.XulEventHandler#getXulDomContainer()
*/
@Override
public XulDomContainer getXulDomContainer() {
return xulDomContainer;
}
@Override
public void setName( String arg0 ) {
}
/*
* (non-Javadoc)
*
* @see org.pentaho.ui.xul.impl.XulEventHandler#setXulDomContainer(org.pentaho.ui.xul.XulDomContainer)
*/
@Override
public void setXulDomContainer( XulDomContainer xulDomContainer ) {
this.xulDomContainer = xulDomContainer;
}
@Override
public boolean canHandleSave() {
return true;
}
@Override
public int showChangedWarning() throws KettleException {
return showChangedWarning( transMeta.getName() );
}
private class StepVelocity {
public StepVelocity( double dx, double dy ) {
this.dx = dx;
this.dy = dy;
}
public double dx, dy;
}
private class StepLocation {
public StepLocation( double x, double y ) {
this.x = x;
this.y = y;
}
public double x, y;
public void add( StepLocation loc ) {
x += loc.x;
y += loc.y;
}
}
private class Force {
public Force( double fx, double fy ) {
this.fx = fx;
this.fy = fy;
}
public double fx, fy;
public void add( Force force ) {
fx += force.fx;
fy += force.fy;
}
}
private static double dampningConstant = 0.5;
// private static double springConstant = 1.0;
private static double timeStep = 1.0;
private static double nodeMass = 1.0;
/**
* Perform an automatic layout of a transformation based on "Force-based algorithms". Source:
* http://en.wikipedia.org/wiki/Force-based_algorithms_(graph_drawing)
* <p/>
* set up initial node velocities to (0,0) set up initial node positions randomly // make sure no 2 nodes are in
* exactly the same position loop total_kinetic_energy := 0 // running sum of total kinetic energy over all particles
* for each node net-force := (0, 0) // running sum of total force on this particular node
* <p/>
* for each other node net-force := net-force + Coulomb_repulsion( this_node, other_node ) next node
* <p/>
* for each spring connected to this node net-force := net-force + Hooke_attraction( this_node, spring ) next spring
* <p/>
* // without damping, it moves forever this_node.velocity := (this_node.velocity + timestep * net-force) * damping
* this_node.position := this_node.position + timestep * this_node.velocity total_kinetic_energy :=
* total_kinetic_energy + this_node.mass * (this_node.velocity)^2 next node until total_kinetic_energy is less than
* some small number // the simulation has stopped moving
*/
public void autoLayout() {
// Initialize...
//
Map<StepMeta, StepVelocity> speeds = new HashMap<>();
Map<StepMeta, StepLocation> locations = new HashMap<>();
for ( StepMeta stepMeta : transMeta.getSteps() ) {
speeds.put( stepMeta, new StepVelocity( 0, 0 ) );
StepLocation location = new StepLocation( stepMeta.getLocation().x, stepMeta.getLocation().y );
locations.put( stepMeta, location );
}
StepLocation center = calculateCenter( locations );
// Layout loop!
//
double totalKineticEngergy = 0;
do {
totalKineticEngergy = 0;
for ( StepMeta stepMeta : transMeta.getSteps() ) {
Force netForce = new Force( 0, 0 );
StepVelocity velocity = speeds.get( stepMeta );
StepLocation location = locations.get( stepMeta );
for ( StepMeta otherStep : transMeta.getSteps() ) {
if ( !stepMeta.equals( otherStep ) ) {
netForce.add( getCoulombRepulsion( stepMeta, otherStep, locations ) );
}
}
for ( int i = 0; i < transMeta.nrTransHops(); i++ ) {
TransHopMeta hopMeta = transMeta.getTransHop( i );
if ( hopMeta.getFromStep().equals( stepMeta ) || hopMeta.getToStep().equals( stepMeta ) ) {
netForce.add( getHookeAttraction( hopMeta, locations ) );
}
}
adjustVelocity( velocity, netForce );
adjustLocation( location, velocity );
totalKineticEngergy += nodeMass * ( velocity.dx * velocity.dx + velocity.dy * velocity.dy );
}
StepLocation newCenter = calculateCenter( locations );
StepLocation diff = new StepLocation( center.x - newCenter.x, center.y - newCenter.y );
for ( StepMeta stepMeta : transMeta.getSteps() ) {
StepLocation location = locations.get( stepMeta );
location.x += diff.x;
location.y += diff.y;
stepMeta.setLocation( (int) Math.round( location.x ), (int) Math.round( location.y ) );
}
// redraw...
//
redraw();
} while ( totalKineticEngergy < 0.01 );
}
private StepLocation calculateCenter( Map<StepMeta, StepLocation> locations ) {
StepLocation center = new StepLocation( 0, 0 );
for ( StepLocation location : locations.values() ) {
center.add( location );
}
center.x /= locations.size();
center.y /= locations.size();
return center;
}
/**
* http://en.wikipedia.org/wiki/Coulomb's_law
*
* @param step1
* @param step2
* @param locations
* @return
*/
private Force getCoulombRepulsion( StepMeta step1, StepMeta step2, Map<StepMeta, StepLocation> locations ) {
double q1 = 4.0;
double q2 = 4.0;
double Ke = -3.0;
StepLocation loc1 = locations.get( step1 );
StepLocation loc2 = locations.get( step2 );
double fx = Ke * q1 * q2 / Math.abs( loc1.x - loc2.x );
double fy = Ke * q1 * q2 / Math.abs( loc1.y - loc2.y );
return new Force( fx, fy );
}
/**
* The longer the hop, the higher the force
*
* @param hopMeta
* @param locations
* @return
*/
private Force getHookeAttraction( TransHopMeta hopMeta, Map<StepMeta, StepLocation> locations ) {
StepLocation loc1 = locations.get( hopMeta.getFromStep() );
StepLocation loc2 = locations.get( hopMeta.getToStep() );
double springConstant = 0.01;
double fx = springConstant * Math.abs( loc1.x - loc2.x );
double fy = springConstant * Math.abs( loc1.y - loc2.y );
return new Force( fx * fx, fy * fy );
}
private void adjustVelocity( StepVelocity velocity, Force netForce ) {
velocity.dx = ( velocity.dx + timeStep * netForce.fx ) * dampningConstant;
velocity.dy = ( velocity.dy + timeStep * netForce.fy ) * dampningConstant;
}
private void adjustLocation( StepLocation location, StepVelocity velocity ) {
location.x = location.x + nodeMass * velocity.dx * velocity.dx;
location.y = location.y + nodeMass * velocity.dy * velocity.dy;
}
public void handleTransMetaChanges( TransMeta transMeta ) throws KettleException {
if ( transMeta.hasChanged() ) {
if ( spoon.props.getAutoSave() ) {
spoon.saveToFile( transMeta );
} else {
MessageDialogWithToggle md =
new MessageDialogWithToggle( shell, BaseMessages.getString( PKG, "TransLog.Dialog.FileHasChanged.Title" ),
null, BaseMessages.getString( PKG, "TransLog.Dialog.FileHasChanged1.Message" ) + Const.CR
+ BaseMessages.getString( PKG, "TransLog.Dialog.FileHasChanged2.Message" ) + Const.CR,
MessageDialog.QUESTION, new String[] { BaseMessages.getString( PKG, "System.Button.Yes" ),
BaseMessages.getString( PKG, "System.Button.No" ) }, 0, BaseMessages.getString( PKG,
"TransLog.Dialog.Option.AutoSaveTransformation" ), spoon.props.getAutoSave() );
MessageDialogWithToggle.setDefaultImage( GUIResource.getInstance().getImageSpoon() );
int answer = md.open();
if ( ( answer & 0xFF ) == 0 ) {
spoon.saveToFile( transMeta );
}
spoon.props.setAutoSave( md.getToggleState() );
}
}
}
private StepMeta lastChained = null;
public void addStepToChain( PluginInterface stepPlugin, boolean shift ) {
TransMeta transMeta = spoon.getActiveTransformation();
if ( transMeta == null ) {
return;
}
// Is the lastChained entry still valid?
//
if ( lastChained != null && transMeta.findStep( lastChained.getName() ) == null ) {
lastChained = null;
}
// If there is exactly one selected step, pick that one as last chained.
//
List<StepMeta> sel = transMeta.getSelectedSteps();
if ( sel.size() == 1 ) {
lastChained = sel.get( 0 );
}
// Where do we add this?
Point p = null;
if ( lastChained == null ) {
p = transMeta.getMaximum();
p.x -= 100;
} else {
p = new Point( lastChained.getLocation().x, lastChained.getLocation().y );
}
p.x += 200;
// Which is the new step?
StepMeta newStep =
spoon.newStep( transMeta, stepPlugin.getIds()[ 0 ], stepPlugin.getName(), stepPlugin.getName(), false, true );
if ( newStep == null ) {
return;
}
newStep.setLocation( p.x, p.y );
newStep.setDraw( true );
if ( lastChained != null ) {
TransHopMeta hop = new TransHopMeta( lastChained, newStep );
spoon.newHop( transMeta, hop );
}
lastChained = newStep;
spoon.refreshGraph();
spoon.refreshTree();
if ( shift ) {
editStep( newStep );
}
transMeta.unselectAll();
newStep.setSelected( true );
}
public Spoon getSpoon() {
return spoon;
}
public void setSpoon( Spoon spoon ) {
this.spoon = spoon;
}
public TransMeta getTransMeta() {
return transMeta;
}
public Trans getTrans() {
return trans;
}
private Trans createLegacyTrans() {
try {
return new Trans( transMeta, spoon.rep, transMeta.getName(),
transMeta.getRepositoryDirectory().getPath(),
transMeta.getFilename(), transMeta);
} catch ( KettleException e ) {
throw new RuntimeException( e );
}
}
private void setHopEnabled( TransHopMeta hop, boolean enabled ) {
hop.setEnabled( enabled );
transMeta.clearCaches();
}
private void modalMessageDialog( String title, String message, int swtFlags ) {
MessageBox messageBox = new MessageBox( shell, swtFlags );
messageBox.setMessage( message );
messageBox.setText( title );
messageBox.open();
}
private String getString( String key ) {
return BaseMessages.getString( PKG, key );
}
private String getString( String key, String... params ) {
return BaseMessages.getString( PKG, key, params );
}
}
| pentaho/pentaho-kettle | ui/src/main/java/org/pentaho/di/ui/spoon/trans/TransGraph.java |
45,347 | package com.taobao.tddl.dbsync.binlog;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.taobao.tddl.dbsync.binlog.event.LogHeader;
/**
* Binary log event definitions. This includes generic code common to all types
* of log events, as well as specific code for each type of log event. - All
* numbers, whether they are 16-, 24-, 32-, or 64-bit numbers, are stored in
* little endian, i.e., the least significant byte first, unless otherwise
* specified. representation of unsigned integers, called Packed Integer. A
* Packed Integer has the capacity of storing up to 8-byte integers, while small
* integers still can use 1, 3, or 4 bytes. The value of the first byte
* determines how to read the number, according to the following table:
* <table>
* <caption>Format of Packed Integer</caption>
* <tr>
* <th>First byte</th>
* <th>Format</th>
* </tr>
* <tr>
* <td>0-250</td>
* <td>The first byte is the number (in the range 0-250), and no more bytes are
* used.</td>
* </tr>
* <tr>
* <td>252</td>
* <td>Two more bytes are used. The number is in the range 251-0xffff.</td>
* </tr>
* <tr>
* <td>253</td>
* <td>Three more bytes are used. The number is in the range 0xffff-0xffffff.</td>
* </tr>
* <tr>
* <td>254</td>
* <td>Eight more bytes are used. The number is in the range
* 0xffffff-0xffffffffffffffff.</td>
* </tr>
* </table>
* - Strings are stored in various formats. The format of each string is
* documented separately.
*
* @see mysql-5.1.60/sql/log_event.h
* @author <a href="mailto:[email protected]">Changyuan.lh</a>
* @version 1.0
*/
public abstract class LogEvent {
/*
* 3 is MySQL 4.x; 4 is MySQL 5.0.0. Compared to version 3, version 4 has: -
* a different Start_log_event, which includes info about the binary log
* (sizes of headers); this info is included for better compatibility if the
* master's MySQL version is different from the slave's. - all events have a
* unique ID (the triplet (server_id, timestamp at server start, other) to
* be sure an event is not executed more than once in a multimaster setup,
* example: M1 / \ v v M2 M3 \ / v v S if a query is run on M1, it will
* arrive twice on S, so we need that S remembers the last unique ID it has
* processed, to compare and know if the event should be skipped or not.
* Example of ID: we already have the server id (4 bytes), plus:
* timestamp_when_the_master_started (4 bytes), a counter (a sequence number
* which increments every time we write an event to the binlog) (3 bytes).
* Q: how do we handle when the counter is overflowed and restarts from 0 ?
* - Query and Load (Create or Execute) events may have a more precise
* timestamp (with microseconds), number of matched/affected/warnings rows
* and fields of session variables: SQL_MODE, FOREIGN_KEY_CHECKS,
* UNIQUE_CHECKS, SQL_AUTO_IS_NULL, the collations and charsets, the
* PASSWORD() version (old/new/...).
*/
public static final int BINLOG_VERSION = 4;
/* Default 5.0 server version */
public static final String SERVER_VERSION = "5.0";
/**
* Event header offsets; these point to places inside the fixed header.
*/
public static final int EVENT_TYPE_OFFSET = 4;
public static final int SERVER_ID_OFFSET = 5;
public static final int EVENT_LEN_OFFSET = 9;
public static final int LOG_POS_OFFSET = 13;
public static final int FLAGS_OFFSET = 17;
/* event-specific post-header sizes */
// where 3.23, 4.x and 5.0 agree
public static final int QUERY_HEADER_MINIMAL_LEN = (4 + 4 + 1 + 2);
// where 5.0 differs: 2 for len of N-bytes vars.
public static final int QUERY_HEADER_LEN = (QUERY_HEADER_MINIMAL_LEN + 2);
/* Enumeration type for the different types of log events. */
public static final int UNKNOWN_EVENT = 0;
public static final int START_EVENT_V3 = 1;
public static final int QUERY_EVENT = 2;
public static final int STOP_EVENT = 3;
public static final int ROTATE_EVENT = 4;
public static final int INTVAR_EVENT = 5;
public static final int LOAD_EVENT = 6;
public static final int SLAVE_EVENT = 7;
public static final int CREATE_FILE_EVENT = 8;
public static final int APPEND_BLOCK_EVENT = 9;
public static final int EXEC_LOAD_EVENT = 10;
public static final int DELETE_FILE_EVENT = 11;
/**
* NEW_LOAD_EVENT is like LOAD_EVENT except that it has a longer sql_ex,
* allowing multibyte TERMINATED BY etc; both types share the same class
* (Load_log_event)
*/
public static final int NEW_LOAD_EVENT = 12;
public static final int RAND_EVENT = 13;
public static final int USER_VAR_EVENT = 14;
public static final int FORMAT_DESCRIPTION_EVENT = 15;
public static final int XID_EVENT = 16;
public static final int BEGIN_LOAD_QUERY_EVENT = 17;
public static final int EXECUTE_LOAD_QUERY_EVENT = 18;
public static final int TABLE_MAP_EVENT = 19;
/**
* These event numbers were used for 5.1.0 to 5.1.15 and are therefore
* obsolete.
*/
public static final int PRE_GA_WRITE_ROWS_EVENT = 20;
public static final int PRE_GA_UPDATE_ROWS_EVENT = 21;
public static final int PRE_GA_DELETE_ROWS_EVENT = 22;
/**
* These event numbers are used from 5.1.16 and forward
*/
public static final int WRITE_ROWS_EVENT_V1 = 23;
public static final int UPDATE_ROWS_EVENT_V1 = 24;
public static final int DELETE_ROWS_EVENT_V1 = 25;
/**
* Something out of the ordinary happened on the master
*/
public static final int INCIDENT_EVENT = 26;
/**
* Heartbeat event to be send by master at its idle time to ensure master's
* online status to slave
*/
public static final int HEARTBEAT_LOG_EVENT = 27;
/**
* In some situations, it is necessary to send over ignorable data to the
* slave: data that a slave can handle in case there is code for handling
* it, but which can be ignored if it is not recognized.
*/
public static final int IGNORABLE_LOG_EVENT = 28;
public static final int ROWS_QUERY_LOG_EVENT = 29;
/** Version 2 of the Row events */
public static final int WRITE_ROWS_EVENT = 30;
public static final int UPDATE_ROWS_EVENT = 31;
public static final int DELETE_ROWS_EVENT = 32;
public static final int GTID_LOG_EVENT = 33;
public static final int ANONYMOUS_GTID_LOG_EVENT = 34;
public static final int PREVIOUS_GTIDS_LOG_EVENT = 35;
/* MySQL 5.7 events */
public static final int TRANSACTION_CONTEXT_EVENT = 36;
public static final int VIEW_CHANGE_EVENT = 37;
/* Prepared XA transaction terminal event similar to Xid */
public static final int XA_PREPARE_LOG_EVENT = 38;
/**
* Extension of UPDATE_ROWS_EVENT, allowing partial values according to
* binlog_row_value_options.
*/
public static final int PARTIAL_UPDATE_ROWS_EVENT = 39;
/* mysql 8.0.20 */
public static final int TRANSACTION_PAYLOAD_EVENT = 40;
/* mysql 8.0.26 */
public static final int HEARTBEAT_LOG_EVENT_V2 = 41;
public static final int MYSQL_ENUM_END_EVENT = 42;
// mariaDb 5.5.34
/* New MySQL/Sun events are to be added right above this comment */
public static final int MYSQL_EVENTS_END = 49;
public static final int MARIA_EVENTS_BEGIN = 160;
/* New Maria event numbers start from here */
public static final int ANNOTATE_ROWS_EVENT = 160;
/*
* Binlog checkpoint event. Used for XA crash recovery on the master, not
* used in replication. A binlog checkpoint event specifies a binlog file
* such that XA crash recovery can start from that file - and it is
* guaranteed to find all XIDs that are prepared in storage engines but not
* yet committed.
*/
public static final int BINLOG_CHECKPOINT_EVENT = 161;
/*
* Gtid event. For global transaction ID, used to start a new event group,
* instead of the old BEGIN query event, and also to mark stand-alone
* events.
*/
public static final int GTID_EVENT = 162;
/*
* Gtid list event. Logged at the start of every binlog, to record the
* current replication state. This consists of the last GTID seen for each
* replication domain.
*/
public static final int GTID_LIST_EVENT = 163;
public static final int START_ENCRYPTION_EVENT = 164;
// mariadb 10.10.1
/*
* Compressed binlog event. Note that the order between WRITE/UPDATE/DELETE
* events is significant; this is so that we can convert from the compressed to
* the uncompressed event type with (type-WRITE_ROWS_COMPRESSED_EVENT +
* WRITE_ROWS_EVENT) and similar for _V1.
*/
public static final int QUERY_COMPRESSED_EVENT = 165;
public static final int WRITE_ROWS_COMPRESSED_EVENT_V1 = 166;
public static final int UPDATE_ROWS_COMPRESSED_EVENT_V1 = 167;
public static final int DELETE_ROWS_COMPRESSED_EVENT_V1 = 168;
public static final int WRITE_ROWS_COMPRESSED_EVENT = 169;
public static final int UPDATE_ROWS_COMPRESSED_EVENT = 170;
public static final int DELETE_ROWS_COMPRESSED_EVENT = 171;
/** end marker */
public static final int ENUM_END_EVENT = 171;
/**
* 1 byte length, 1 byte format Length is total length in bytes, including 2
* byte header Length values 0 and 1 are currently invalid and reserved.
*/
public static final int EXTRA_ROW_INFO_LEN_OFFSET = 0;
public static final int EXTRA_ROW_INFO_FORMAT_OFFSET = 1;
public static final int EXTRA_ROW_INFO_HDR_BYTES = 2;
public static final int EXTRA_ROW_INFO_MAX_PAYLOAD = (255 - EXTRA_ROW_INFO_HDR_BYTES);
// Events are without checksum though its generator
public static final int BINLOG_CHECKSUM_ALG_OFF = 0;
// is checksum-capable New Master (NM).
// CRC32 of zlib algorithm.
public static final int BINLOG_CHECKSUM_ALG_CRC32 = 1;
// the cut line: valid alg range is [1, 0x7f].
public static final int BINLOG_CHECKSUM_ALG_ENUM_END = 2;
// special value to tag undetermined yet checksum
public static final int BINLOG_CHECKSUM_ALG_UNDEF = 255;
// or events from checksum-unaware servers
public static final int CHECKSUM_CRC32_SIGNATURE_LEN = 4;
public static final int BINLOG_CHECKSUM_ALG_DESC_LEN = 1;
/**
* defined statically while there is just one alg implemented
*/
public static final int BINLOG_CHECKSUM_LEN = CHECKSUM_CRC32_SIGNATURE_LEN;
/* MySQL or old MariaDB slave with no announced capability. */
public static final int MARIA_SLAVE_CAPABILITY_UNKNOWN = 0;
/* MariaDB >= 5.3, which understands ANNOTATE_ROWS_EVENT. */
public static final int MARIA_SLAVE_CAPABILITY_ANNOTATE = 1;
/*
* MariaDB >= 5.5. This version has the capability to tolerate events
* omitted from the binlog stream without breaking replication (MySQL slaves
* fail because they mis-compute the offsets into the master's binlog).
*/
public static final int MARIA_SLAVE_CAPABILITY_TOLERATE_HOLES = 2;
/* MariaDB >= 10.0, which knows about binlog_checkpoint_log_event. */
public static final int MARIA_SLAVE_CAPABILITY_BINLOG_CHECKPOINT = 3;
/* MariaDB >= 10.0.1, which knows about global transaction id events. */
public static final int MARIA_SLAVE_CAPABILITY_GTID = 4;
/* Our capability. */
public static final int MARIA_SLAVE_CAPABILITY_MINE = MARIA_SLAVE_CAPABILITY_GTID;
/**
* For an event, 'e', carrying a type code, that a slave, 's', does not
* recognize, 's' will check 'e' for LOG_EVENT_IGNORABLE_F, and if the flag
* is set, then 'e' is ignored. Otherwise, 's' acknowledges that it has
* found an unknown event in the relay log.
*/
public static final int LOG_EVENT_IGNORABLE_F = 0x80;
/** enum_field_types */
public static final int MYSQL_TYPE_DECIMAL = 0;
public static final int MYSQL_TYPE_TINY = 1;
public static final int MYSQL_TYPE_SHORT = 2;
public static final int MYSQL_TYPE_LONG = 3;
public static final int MYSQL_TYPE_FLOAT = 4;
public static final int MYSQL_TYPE_DOUBLE = 5;
public static final int MYSQL_TYPE_NULL = 6;
public static final int MYSQL_TYPE_TIMESTAMP = 7;
public static final int MYSQL_TYPE_LONGLONG = 8;
public static final int MYSQL_TYPE_INT24 = 9;
public static final int MYSQL_TYPE_DATE = 10;
public static final int MYSQL_TYPE_TIME = 11;
public static final int MYSQL_TYPE_DATETIME = 12;
public static final int MYSQL_TYPE_YEAR = 13;
public static final int MYSQL_TYPE_NEWDATE = 14;
public static final int MYSQL_TYPE_VARCHAR = 15;
public static final int MYSQL_TYPE_BIT = 16;
public static final int MYSQL_TYPE_TIMESTAMP2 = 17;
public static final int MYSQL_TYPE_DATETIME2 = 18;
public static final int MYSQL_TYPE_TIME2 = 19;
public static final int MYSQL_TYPE_TYPED_ARRAY = 20;
public static final int MYSQL_TYPE_INVALID = 243;
public static final int MYSQL_TYPE_BOOL = 244;
public static final int MYSQL_TYPE_JSON = 245;
public static final int MYSQL_TYPE_NEWDECIMAL = 246;
public static final int MYSQL_TYPE_ENUM = 247;
public static final int MYSQL_TYPE_SET = 248;
public static final int MYSQL_TYPE_TINY_BLOB = 249;
public static final int MYSQL_TYPE_MEDIUM_BLOB = 250;
public static final int MYSQL_TYPE_LONG_BLOB = 251;
public static final int MYSQL_TYPE_BLOB = 252;
public static final int MYSQL_TYPE_VAR_STRING = 253;
public static final int MYSQL_TYPE_STRING = 254;
public static final int MYSQL_TYPE_GEOMETRY = 255;
public static String getTypeName(final int type) {
switch (type) {
case START_EVENT_V3:
return "Start_v3";
case STOP_EVENT:
return "Stop";
case QUERY_EVENT:
return "Query";
case ROTATE_EVENT:
return "Rotate";
case INTVAR_EVENT:
return "Intvar";
case LOAD_EVENT:
return "Load";
case NEW_LOAD_EVENT:
return "New_load";
case SLAVE_EVENT:
return "Slave";
case CREATE_FILE_EVENT:
return "Create_file";
case APPEND_BLOCK_EVENT:
return "Append_block";
case DELETE_FILE_EVENT:
return "Delete_file";
case EXEC_LOAD_EVENT:
return "Exec_load";
case RAND_EVENT:
return "RAND";
case XID_EVENT:
return "Xid";
case USER_VAR_EVENT:
return "User var";
case FORMAT_DESCRIPTION_EVENT:
return "Format_desc";
case TABLE_MAP_EVENT:
return "Table_map";
case PRE_GA_WRITE_ROWS_EVENT:
return "Write_rows_event_old";
case PRE_GA_UPDATE_ROWS_EVENT:
return "Update_rows_event_old";
case PRE_GA_DELETE_ROWS_EVENT:
return "Delete_rows_event_old";
case WRITE_ROWS_EVENT_V1:
return "Write_rows_v1";
case UPDATE_ROWS_EVENT_V1:
return "Update_rows_v1";
case DELETE_ROWS_EVENT_V1:
return "Delete_rows_v1";
case BEGIN_LOAD_QUERY_EVENT:
return "Begin_load_query";
case EXECUTE_LOAD_QUERY_EVENT:
return "Execute_load_query";
case INCIDENT_EVENT:
return "Incident";
case HEARTBEAT_LOG_EVENT:
case HEARTBEAT_LOG_EVENT_V2:
return "Heartbeat";
case IGNORABLE_LOG_EVENT:
return "Ignorable";
case ROWS_QUERY_LOG_EVENT:
return "Rows_query";
case WRITE_ROWS_EVENT:
return "Write_rows";
case UPDATE_ROWS_EVENT:
return "Update_rows";
case DELETE_ROWS_EVENT:
return "Delete_rows";
case GTID_LOG_EVENT:
return "Gtid";
case ANONYMOUS_GTID_LOG_EVENT:
return "Anonymous_Gtid";
case PREVIOUS_GTIDS_LOG_EVENT:
return "Previous_gtids";
case PARTIAL_UPDATE_ROWS_EVENT:
return "Update_rows_partial";
case TRANSACTION_CONTEXT_EVENT :
return "Transaction_context";
case VIEW_CHANGE_EVENT :
return "view_change";
case XA_PREPARE_LOG_EVENT :
return "Xa_prepare";
case TRANSACTION_PAYLOAD_EVENT :
return "transaction_payload";
default:
return "Unknown type:" + type;
}
}
protected static final Log logger = LogFactory.getLog(LogEvent.class);
protected final LogHeader header;
/**
* mysql半同步semi标识
*
* <pre>
* 0不需要semi ack 给mysql
* 1需要semi ack给mysql
* </pre>
*/
protected int semival;
public int getSemival() {
return semival;
}
public void setSemival(int semival) {
this.semival = semival;
}
protected LogEvent(LogHeader header){
this.header = header;
}
/**
* Return event header.
*/
public final LogHeader getHeader() {
return header;
}
/**
* The total size of this event, in bytes. In other words, this is the sum
* of the sizes of Common-Header, Post-Header, and Body.
*/
public final int getEventLen() {
return header.getEventLen();
}
/**
* Server ID of the server that created the event.
*/
public final long getServerId() {
return header.getServerId();
}
/**
* The position of the next event in the master binary log, in bytes from
* the beginning of the file. In a binlog that is not a relay log, this is
* just the position of the next event, in bytes from the beginning of the
* file. In a relay log, this is the position of the next event in the
* master's binlog.
*/
public final long getLogPos() {
return header.getLogPos();
}
/**
* The time when the query started, in seconds since 1970.
*/
public final long getWhen() {
return header.getWhen();
}
}
| alibaba/canal | dbsync/src/main/java/com/taobao/tddl/dbsync/binlog/LogEvent.java |
45,348 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.api;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.util.containers.Convertor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.jetbrains.idea.svn.SvnBundle.message;
public class FileStatusResultParser {
@NotNull
private final Pattern myLinePattern;
@Nullable
private final ProgressTracker handler;
@NotNull
private final Convertor<Matcher, ProgressEvent> myConvertor;
public FileStatusResultParser(@NotNull Pattern linePattern,
@Nullable ProgressTracker handler,
@NotNull Convertor<Matcher, ProgressEvent> convertor) {
myLinePattern = linePattern;
this.handler = handler;
myConvertor = convertor;
}
public void parse(@NotNull String output) throws VcsException {
if (StringUtil.isEmpty(output)) {
return;
}
for (String line : StringUtil.splitByLines(output)) {
onLine(line);
}
}
public void onLine(@NotNull String line) throws VcsException {
Matcher matcher = myLinePattern.matcher(line);
if (matcher.matches()) {
process(matcher);
}
else {
throw new VcsException(message("error.parse.file.status.unknown.state.on.line", line));
}
}
public void process(@NotNull Matcher matcher) throws VcsException {
if (handler != null) {
handler.consume(myConvertor.convert(matcher));
}
}
}
| JLLeitschuh/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/api/FileStatusResultParser.java |
45,349 | package edu.stanford.nlp.sequences;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.optimization.StochasticCalculateMethods;
import edu.stanford.nlp.process.WordShapeClassifier;
import edu.stanford.nlp.util.ReflectionLoading;
import edu.stanford.nlp.util.logging.Redwood;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Function;
/**
* Flags for sequence classifiers. Documentation for general flags and
* flags for NER can be found in the Javadoc of
* {@link edu.stanford.nlp.ie.NERFeatureFactory}. Documentation for the flags
* for Chinese word segmentation can be found in the Javadoc of
* {@link edu.stanford.nlp.wordseg.ChineseSegmenterFeatureFactory}.
*
* <i>IMPORTANT NOTE IF CHANGING THIS FILE:</i> <b>MAKE SURE</b> TO
* ONLY ADD NEW VARIABLES AT THE END OF THE LIST OF VARIABLES (and not
* to change existing variables)! Otherwise you usually break all
* currently serialized classifiers!!! Search for "ADD VARIABLES ABOVE
* HERE" below.
*
* Some general flags are described here
* <table border="1">
* <caption>Flags for sequence classifiers</caption>
* <tr>
* <td><b>Property Name</b></td>
* <td><b>Type</b></td>
* <td><b>Default Value</b></td>
* <td><b>Description</b></td>
* </tr>
* <tr>
* <td>useQN</td>
* <td>boolean</td>
* <td>true</td>
* <td>Use Quasi-Newton (L-BFGS) optimization to find minimum. NOTE: Need to set this to
* false if using other minimizers such as SGD.</td>
* </tr>
* <tr>
* <td>QNsize</td>
* <td>int</td>
* <td>25</td>
* <td>Number of previous iterations of Quasi-Newton to store (this increases
* memory use, but speeds convergence by letting the Quasi-Newton optimization
* more effectively approximate the second derivative).</td>
* </tr>
* <tr>
* <td>QNsize2</td>
* <td>int</td>
* <td>25</td>
* <td>Number of previous iterations of Quasi-Newton to store (used when pruning
* features, after the first iteration - the first iteration is with QNSize).</td>
* </tr>
* <tr>
* <td>useInPlaceSGD</td>
* <td>boolean</td>
* <td>false</td>
* <td>Use SGD (tweaking weights in place) to find minimum (more efficient than
* the old SGD, faster to converge than Quasi-Newton if there are very large of
* samples). Implemented for CRFClassifier. NOTE: Remember to set useQN to false
* </td>
* </tr>
* <tr>
* <td>tuneSampleSize</td>
* <td>int</td>
* <td>-1</td>
* <td>If this number is greater than 0, specifies the number of samples to use
* for tuning (default is 1000).</td>
* </tr>
* <tr>
* <td>SGDPasses</td>
* <td>int</td>
* <td>-1</td>
* <td>If this number is greater than 0, specifies the number of SGD passes over
* entire training set) to do before giving up (default is 50). Can be smaller
* if sample size is very large.</td>
* </tr>
* <tr>
* <td>useSGD</td>
* <td>boolean</td>
* <td>false</td>
* <td>Use SGD to find minimum (can be slow). NOTE: Remember to set useQN to
* false</td>
* </tr>
* <tr>
* <td>useSGDtoQN</td>
* <td>boolean</td>
* <td>false</td>
* <td>Use SGD (SGD version selected by useInPlaceSGD or useSGD) for a certain
* number of passes (SGDPasses) and then switches to QN. Gives the quick initial
* convergence of SGD, with the desired convergence criterion of QN (there is
* some ramp up time for QN). NOTE: Remember to set useQN to false</td>
* </tr>
* <tr>
* <td>evaluateIters</td>
* <td>int</td>
* <td>0</td>
* <td>If this number is greater than 0, evaluates on the test set every so
* often while minimizing. Implemented for CRFClassifier.</td>
* </tr>
* <tr>
* <td>evalCmd</td>
* <td>String</td>
* <td></td>
* <td>If specified (and evaluateIters is set), runs the specified cmdline
* command during evaluation (instead of default CONLL-like NER evaluation)</td>
* </tr>
* <tr>
* <td>evaluateTrain</td>
* <td>boolean</td>
* <td>false</td>
* <td>If specified (and evaluateIters is set), also evaluate on training set
* (can be expensive)</td>
* </tr>
* <tr>
* <td>tokenizerOptions</td><td>String</td>
* <td>(null)</td>
* <td>Extra options to supply to the tokenizer when creating it.</td>
* </tr>
* <tr>
* <td>tokenizerFactory</td><td>String</td>
* <td>(null)</td>
* <td>A different tokenizer factory to use if the ReaderAndWriter in question uses tokenizers.</td>
* </tr>
* </table>
*
* @author Jenny Finkel
*/
public class SeqClassifierFlags implements Serializable {
/** A logger for this class */
private static final Redwood.RedwoodChannels log = Redwood.channels(SeqClassifierFlags.class);
private static final long serialVersionUID = -7076671761070232567L;
public static final String DEFAULT_BACKGROUND_SYMBOL = "O";
private String stringRep = "";
public boolean useNGrams = false;
public boolean conjoinShapeNGrams = false;
public boolean lowercaseNGrams = false;
public boolean dehyphenateNGrams = false;
public boolean usePrev = false;
public boolean useNext = false;
public boolean useTags = false;
public boolean useWordPairs = false;
public boolean useGazettes = false;
public boolean useSequences = true;
public boolean usePrevSequences = false;
public boolean useNextSequences = false;
public boolean useLongSequences = false;
public boolean useBoundarySequences = false;
public boolean useTaggySequences = false;
public boolean useExtraTaggySequences = false;
public boolean dontExtendTaggy = false;
public boolean useTaggySequencesShapeInteraction = false;
public boolean strictlyZeroethOrder = false;
public boolean strictlyFirstOrder = false;
public boolean strictlySecondOrder = false;
public boolean strictlyThirdOrder = false;
public String entitySubclassification = "IO";
public boolean retainEntitySubclassification = false;
public boolean useGazettePhrases = false;
public boolean makeConsistent = false;
public boolean useViterbi = true;
public int[] binnedLengths = null;
public boolean verboseMode = false;
public boolean useSum = false;
public double tolerance = 1e-4;
// Turned on if non-null. Becomes part of the filename features are printed to.
// The meaning of this option varies between classifiers (see exportFeatures for another option):
// - CMMClassifier: print the features of each datum
// - CRFClassifier: just dump the list of feature names for the whole dataset
public String printFeatures = null;
public boolean useSymTags = false;
/**
* useSymWordPairs Has a small negative effect.
*/
public boolean useSymWordPairs = false;
public String printClassifier = "WeightHistogram";
public int printClassifierParam = 100;
public boolean intern = false;
public boolean intern2 = false;
public boolean selfTest = false;
public boolean sloppyGazette = false;
public boolean cleanGazette = false;
public boolean noMidNGrams = false;
public int maxNGramLeng = -1;
public boolean useReverse = false;
public boolean greekifyNGrams = false;
public boolean useParenMatching = false;
public boolean useLemmas = false;
public boolean usePrevNextLemmas = false;
public boolean normalizeTerms = false;
public boolean normalizeTimex = false;
public boolean useNB = false;
public boolean useQN = true;
public boolean useFloat = false;
public int QNsize = 25;
public int QNsize2 = 25;
public int maxIterations = -1;
public int wordShape = WordShapeClassifier.NOWORDSHAPE;
/** Set useShapeStrings to be true to say that the model should use word shape features and they are provided in
* the tokens, but should not be calculated via a word shape function. This flag must be false if the word shape
* features will be calculated; word shape features are also added if there is a defined word shape function.
*/
public boolean useShapeStrings = false;
public boolean useTypeSeqs = false;
public boolean useTypeSeqs2 = false;
public boolean useTypeSeqs3 = false;
public boolean useDisjunctive = false;
public int disjunctionWidth = 4;
public boolean useDisjunctiveShapeInteraction = false;
public boolean useDisjShape = false;
public boolean useWord = true; // ON by default
public boolean useClassFeature = false;
public boolean useShapeConjunctions = false;
public boolean useWordTag = false;
public boolean useNPHead = false;
public boolean useNPGovernor = false;
public boolean useHeadGov = false;
public boolean useLastRealWord = false;
public boolean useNextRealWord = false;
public boolean useOccurrencePatterns = false;
public boolean useTypeySequences = false;
public boolean justify = false;
public boolean normalize = false;
public String priorType = "QUADRATIC";
public double sigma = 1.0;
public double epsilon = 0.01;
public int beamSize = 30;
public int maxLeft = 2;
public int maxRight = 0;
public boolean usePosition = false;
public boolean useBeginSent = false;
public boolean useGazFeatures = false;
public boolean useMoreGazFeatures = false;
public boolean useAbbr = false;
public boolean useMinimalAbbr = false;
public boolean useAbbr1 = false;
public boolean useMinimalAbbr1 = false;
public boolean useMoreAbbr = false;
public boolean deleteBlankLines = false;
public boolean useGENIA = false;
public boolean useTOK = false;
public boolean useABSTR = false;
public boolean useABSTRFreqDict = false;
public boolean useABSTRFreq = false;
public boolean useFREQ = false;
public boolean useABGENE = false;
public boolean useWEB = false;
public boolean useWEBFreqDict = false;
public boolean useIsURL = false;
public boolean useURLSequences = false;
public boolean useIsDateRange = false;
public boolean useEntityTypes = false;
public boolean useEntityTypeSequences = false;
public boolean useEntityRule = false;
public boolean useOrdinal = false;
public boolean useACR = false;
public boolean useANTE = false;
public boolean useMoreTags = false;
public boolean useChunks = false;
public boolean useChunkySequences = false;
public boolean usePrevVB = false;
public boolean useNextVB = false;
public boolean useVB = false;
public boolean subCWGaz = false;
// TODO OBSOLETE: delete when breaking serialization sometime.
public String documentReader = "ColumnDocumentReader";
// public String trainMap = "word=0,tag=1,answer=2";
// public String testMap = "word=0,tag=1,answer=2";
public String map = "word=0,tag=1,answer=2";
public boolean useWideDisjunctive = false;
public int wideDisjunctionWidth = 10;
// chinese word-segmenter features
public boolean useRadical = false;
public boolean useBigramInTwoClique = false;
public String morphFeatureFile = null;
public boolean useReverseAffix = false;
public int charHalfWindow = 3;
public boolean useWord1 = false;
public boolean useWord2 = false;
public boolean useWord3 = false;
public boolean useWord4 = false;
public boolean useRad1 = false;
public boolean useRad2 = false;
public boolean useWordn = false;
public boolean useCTBPre1 = false;
public boolean useCTBSuf1 = false;
public boolean useASBCPre1 = false;
public boolean useASBCSuf1 = false;
public boolean usePKPre1 = false;
public boolean usePKSuf1 = false;
public boolean useHKPre1 = false;
public boolean useHKSuf1 = false;
public boolean useCTBChar2 = false;
public boolean useASBCChar2 = false;
public boolean useHKChar2 = false;
public boolean usePKChar2 = false;
public boolean useRule2 = false;
public boolean useDict2 = false;
public boolean useOutDict2 = false;
public String outDict2 = "/u/htseng/scr/chunking/segmentation/out.lexicon";
public boolean useDictleng = false;
public boolean useDictCTB2 = false;
public boolean useDictASBC2 = false;
public boolean useDictPK2 = false;
public boolean useDictHK2 = false;
public boolean useBig5 = false;
public boolean useNegDict2 = false;
public boolean useNegDict3 = false;
public boolean useNegDict4 = false;
public boolean useNegCTBDict2 = false;
public boolean useNegCTBDict3 = false;
public boolean useNegCTBDict4 = false;
public boolean useNegASBCDict2 = false;
public boolean useNegASBCDict3 = false;
public boolean useNegASBCDict4 = false;
public boolean useNegHKDict2 = false;
public boolean useNegHKDict3 = false;
public boolean useNegHKDict4 = false;
public boolean useNegPKDict2 = false;
public boolean useNegPKDict3 = false;
public boolean useNegPKDict4 = false;
public boolean usePre = false;
public boolean useSuf = false;
public boolean useRule = false;
public boolean useHk = false;
public boolean useMsr = false;
public boolean useMSRChar2 = false;
public boolean usePk = false;
public boolean useAs = false;
public boolean useFilter = false; // TODO this flag is used for nothing;
// delete when breaking serialization
public boolean largeChSegFile = false; // TODO this flag is used for nothing;
// delete when breaking serialization
public boolean useRad2b = false;
/**
* Keep the whitespace between English words in testFile when printing out
* answers. Doesn't really change the content of the CoreLabels. (For Chinese
* segmentation.)
*/
public boolean keepEnglishWhitespaces = false;
/**
* Keep all the whitespace words in testFile when printing out answers.
* Doesn't really change the content of the CoreLabels. (For Chinese
* segmentation.)
*/
public boolean keepAllWhitespaces = false;
public boolean sighanPostProcessing = false;
/**
* use POS information (an "open" feature for Chinese segmentation)
*/
public boolean useChPos = false;
// CTBSegDocumentReader normalization table
// A value of null means that a default algorithmic normalization
// is done in which ASCII characters get mapped to their fullwidth
// equivalents in the Unihan range
public String normalizationTable; // = null;
public String dictionary; // = null;
public String serializedDictionary; // = null;
public String dictionary2; // = null;
public String normTableEncoding = "GB18030";
/**
* for Sighan bakeoff 2005, the path to the dictionary of bigrams appeared in
* corpus
*/
public String sighanCorporaDict = "/u/nlp/data/chinese-segmenter/";
// end Sighan 20005 chinese word-segmenter features/properties
public boolean useWordShapeGaz = false;
public String wordShapeGaz = null;
// TODO: This should be removed in favor of suppressing splitting when
// maxDocSize <= 0, when next breaking serialization
// this now controls nothing
public boolean splitDocuments = true;
public boolean printXML; // This is disused and can be removed when breaking serialization
public boolean useSeenFeaturesOnly = false;
public String lastNameList = "/u/nlp/data/dist.all.last";
public String maleNameList = "/u/nlp/data/dist.male.first";
public String femaleNameList = "/u/nlp/data/dist.female.first";
// don't want these serialized
public transient String trainFile = null;
/** NER adaptation (Gaussian prior) parameters. */
public transient String adaptFile = null;
public transient String devFile = null;
public transient String testFile = null;
public transient String textFile = null;
public transient String textFiles = null;
public transient boolean readStdin = false;
public transient String outputFile = null;
public transient String loadClassifier = null;
public transient String loadTextClassifier = null;
public transient String loadJarClassifier = null;
public transient String loadAuxClassifier = null;
public transient String serializeTo = null;
public transient String serializeToText = null;
public transient int interimOutputFreq = 0;
public transient String initialWeights = null;
public transient List<String> gazettes = new ArrayList<>();
public transient String selfTrainFile = null;
public String inputEncoding = "UTF-8"; // used for CTBSegDocumentReader as well
public boolean bioSubmitOutput = false;
public int numRuns = 1;
public String answerFile = null;
public String altAnswerFile = null;
public String dropGaz;
public String printGazFeatures = null;
public int numStartLayers = 1;
public boolean dump = false;
// whether to merge B- and I- tags in an input file and to tag with IO tags
// (lacking a prefix). E.g., "I-PERS" goes to "PERS"
public boolean mergeTags;
public boolean splitOnHead;
// threshold
public int featureCountThreshold = 0;
public double featureWeightThreshold = 0.0;
// feature factory
public String featureFactory = "edu.stanford.nlp.ie.NERFeatureFactory";
public Object[] featureFactoryArgs = new Object[0];
public String backgroundSymbol = DEFAULT_BACKGROUND_SYMBOL;
// use
public boolean useObservedSequencesOnly = false;
public int maxDocSize = 0;
public boolean printProbs = false;
public boolean printFirstOrderProbs = false;
public boolean saveFeatureIndexToDisk = false;
public boolean removeBackgroundSingletonFeatures = false;
public boolean doGibbs = false;
public int numSamples = 100;
public boolean useNERPrior = false; // todo [cdm 2014]: Disused, to be deleted, use priorModelFactory
public boolean useAcqPrior = false; // todo [cdm 2014]: Disused, to be deleted, use priorModelFactory
public boolean useUniformPrior = false; // todo [cdm 2014]: Disused, to be deleted, use priorModelFactory
public boolean useMUCFeatures = false;
public double annealingRate = 0.0;
public String annealingType = null;
public String loadProcessedData = null;
public boolean initViterbi = true;
public boolean useUnknown = false;
public boolean checkNameList = false;
public boolean useSemPrior = false; // todo [cdm 2014]: Disused, to be deleted, use priorModelFactory
public boolean useFirstWord = false;
public boolean useNumberFeature = false;
public int ocrFold = 0;
public transient boolean ocrTrain = false; // CDM 2017: Disused. Can delete....
public String classifierType = "MaxEnt";
public String svmModelFile = null;
public String inferenceType = "Viterbi";
public boolean useLemmaAsWord = false;
public String type = "cmm";
public String readerAndWriter = "edu.stanford.nlp.sequences.ColumnDocumentReaderAndWriter";
public List<String> comboProps = new ArrayList<>();
public boolean usePrediction = false;
public boolean useAltGazFeatures = false;
public String gazFilesFile = null;
public boolean usePrediction2 = false;
public String baseTrainDir = ".";
public String baseTestDir = ".";
/** A regex pattern for files, which will be evaluated within a particular directory.
* If non-null, used over trainFileList and trainFile.
*/
public String trainFiles = null;
public String trainFileList = null;
public String testFiles = null;
public String trainDirs = null; // cdm 2009: this is currently unsupported,
// but one user wanted something like this....
public String testDirs = null;
public boolean useOnlySeenWeights = false;
public String predProp = null;
public CoreLabel pad = new CoreLabel();
public boolean useObservedFeaturesOnly = false;
public String distSimLexicon = null;
public boolean useDistSim = false;
public int removeTopN = 0;
public int numTimesRemoveTopN = 1;
public double randomizedRatio = 1.0;
public double removeTopNPercent = 0.0;
public int purgeFeatures = -1;
public boolean booleanFeatures = false;
// This flag is only used for the sequences Type 2 CRF, not for ie.crf.CRFClassifier
public boolean iobWrapper = false;
public boolean iobTags = false;
/** Binary segmentation feature for character-based Chinese NER. */
public boolean useSegmentation = false;
public boolean memoryThrift = false;
public boolean timitDatum = false;
public String serializeDatasetsDir = null;
public String loadDatasetsDir = null;
public String pushDir = null;
public boolean purgeDatasets = false;
public boolean keepOBInMemory = true;
public boolean fakeDataset = false;
public boolean restrictTransitionsTimit = false;
public int numDatasetsPerFile = 1;
public boolean useTitle = false;
// these are for the old stuff
public boolean lowerNewgeneThreshold = false;
public boolean useEitherSideWord = false;
public boolean useEitherSideDisjunctive = false;
public boolean twoStage = false;
public String crfType = "MaxEnt";
public int featureThreshold = 1;
public String featThreshFile = null;
public double featureDiffThresh = 0.0;
public int numTimesPruneFeatures = 0;
public double newgeneThreshold = 0.0;
public boolean doAdaptation = false;
public boolean useInternal = true;
public boolean useExternal = true;
public double selfTrainConfidenceThreshold = 0.9;
public int selfTrainIterations = 1;
public int selfTrainWindowSize = 1; // Unigram
public boolean useHuber = false;
public boolean useQuartic = false;
public double adaptSigma = 1.0;
public int numFolds = 1;
public int startFold = 1;
public int endFold = 1;
public boolean cacheNGrams = false;
public String outputFormat;
public boolean useSMD = false;
public boolean useSGDtoQN = false;
public boolean useStochasticQN = false;
public boolean useScaledSGD = false;
public int scaledSGDMethod = 0;
public int SGDPasses = -1;
public int QNPasses = -1;
public boolean tuneSGD = false;
public StochasticCalculateMethods stochasticMethod = StochasticCalculateMethods.NoneSpecified;
public double initialGain = 0.1;
public int stochasticBatchSize = 15;
public boolean useSGD = false;
public double gainSGD = 0.1;
public boolean useHybrid = false;
public int hybridCutoffIteration = 0;
public boolean outputIterationsToFile = false;
public boolean testObjFunction = false;
public boolean testVariance = false;
public int SGD2QNhessSamples = 50;
public boolean testHessSamples = false;
public int CRForder = 1; // TODO remove this when breaking serialization; this is unused; really maxLeft/maxRight control order
public int CRFwindow = 2; // TODO remove this when breaking serialization; this is unused; really maxLeft/maxRight control clique size
public boolean estimateInitial = false;
public transient String biasedTrainFile = null;
public transient String confusionMatrix = null;
public String outputEncoding = null;
public boolean useKBest = false;
public String searchGraphPrefix = null;
public double searchGraphPrune = Double.POSITIVE_INFINITY;
public int kBest = 1;
// more chinese segmenter features for GALE 2007
public boolean useFeaturesC4gram;
public boolean useFeaturesC5gram;
public boolean useFeaturesC6gram;
public boolean useFeaturesCpC4gram;
public boolean useFeaturesCpC5gram;
public boolean useFeaturesCpC6gram;
public boolean useUnicodeType;
public boolean useUnicodeType4gram;
public boolean useUnicodeType5gram;
public boolean use4Clique;
public boolean useUnicodeBlock;
public boolean useShapeStrings1;
public boolean useShapeStrings3;
public boolean useShapeStrings4;
public boolean useShapeStrings5;
public boolean useGoodForNamesCpC;
public boolean useDictionaryConjunctions;
public boolean expandMidDot;
// Only print the features for the first this many tokens encountered
public int printFeaturesUpto = Integer.MAX_VALUE;
public boolean useDictionaryConjunctions3;
public boolean useWordUTypeConjunctions2;
public boolean useWordUTypeConjunctions3;
public boolean useWordShapeConjunctions2;
public boolean useWordShapeConjunctions3;
public boolean useMidDotShape;
public boolean augmentedDateChars;
public boolean suppressMidDotPostprocessing;
public boolean printNR; // a flag for WordAndTagDocumentReaderAndWriter
public String classBias = null;
public boolean printLabelValue; // Old printErrorStuff
public boolean useRobustQN = false;
public boolean combo = false;
public boolean useGenericFeatures = false;
public boolean verboseForTrueCasing = false;
public String trainHierarchical = null;
public String domain = null;
public boolean baseline = false;
public String transferSigmas = null;
public boolean doFE = false;
public boolean restrictLabels = true;
// whether to print a line saying each ObjectBank entry (usually a filename)
public boolean announceObjectBankEntries = false;
// This is for use with the OWLQNMinimizer L1 regularization. To use it, set useQN=false,
// and this to a positive number. A smaller number means more features are retained.
// Depending on the problem, a good value might be
// between 0.75 (POS tagger) down to 0.01 (Chinese word segmentation)
public double l1reg = 0.0;
// truecaser flags:
public String mixedCaseMapFile = "";
public String auxTrueCaseModels = "";
// more flags inspired by Zhang and Johnson 2003
public boolean use2W = false;
public boolean useLC = false;
public boolean useYetMoreCpCShapes = false;
// added for the NFL domain
public boolean useIfInteger = false;
// Filename to which the features generated by a CRF classify will be exported (if non-null)
public String exportFeatures = null;
public boolean useInPlaceSGD = false;
public boolean useTopics = false;
// Number of iterations before evaluating weights (0 = don't evaluate)
public int evaluateIters = 0;
// Command to use for evaluation
public String evalCmd = "";
// Evaluate on training set or not
public boolean evaluateTrain = false;
public int tuneSampleSize = -1;
public boolean usePhraseFeatures = false;
public boolean usePhraseWords = false;
public boolean usePhraseWordTags = false;
public boolean usePhraseWordSpecialTags = false;
public boolean useCommonWordsFeature = false;
public boolean useProtoFeatures = false;
public boolean useWordnetFeatures = false;
public String tokenFactory = "edu.stanford.nlp.process.CoreLabelTokenFactory";
public Object[] tokenFactoryArgs = new Object[0];
public String tokensAnnotationClassName = "edu.stanford.nlp.ling.CoreAnnotations$TokensAnnotation";
public transient String tokenizerOptions = null;
public transient String tokenizerFactory = null;
public boolean useCorefFeatures = false;
public String wikiFeatureDbFile = null;
// for combining 2 CRFs - one trained from noisy data and another trained from
// non-noisy
public boolean useNoisyNonNoisyFeature = false;
// year annotation of the document
public boolean useYear = false;
public boolean useSentenceNumber = false;
// to know source of the label. Currently, used to know which pattern is used
// to label the token
public boolean useLabelSource = false;
/**
* Whether to (not) lowercase tokens before looking them up in distsim
* lexicon. By default lowercasing was done, but now it doesn't have to be
* true :-).
*/
public boolean casedDistSim = false;
/**
* The format of the distsim file. Known values are: alexClark = TSV file.
* word TAB clusterNumber [optional other content] terryKoo = TSV file.
* clusterBitString TAB word TAB frequency
*/
public String distSimFileFormat = "alexClark";
/**
* If this number is greater than 0, the distSim class is assume to be a bit
* string and is truncated at this many characters. Normal distSim features
* will then use this amount of resolution. Extra, special distsim features
* may work at a coarser level of resolution. Since the lexicon only stores
* this length of bit string, there is then no way to have finer-grained
* clusters.
*/
public int distSimMaxBits = 8;
/**
* If this is set to true, all digit characters get mapped to '9' in a distsim
* lexicon and for lookup. This is a simple word shaping that can shrink
* distsim lexicons and improve their performance.
*/
public boolean numberEquivalenceDistSim = false;
/**
* What class to assign to words not found in the dist sim lexicon. You might
* want to make it a known class, if one is the "default class.
*/
public String unknownWordDistSimClass = "null";
/**
* Use prefixes and suffixes from the previous and current word in edge clique.
*/
public boolean useNeighborNGrams = false;
/**
* This function maps words in the training or test data to new
* words. They are used at the feature extractor level, ie in the
* FeatureFactory. For now, only the NERFeatureFactory uses this.
*/
public Function<String, String> wordFunction = null;
public static final String DEFAULT_PLAIN_TEXT_READER = "edu.stanford.nlp.sequences.PlainTextDocumentReaderAndWriter";
public String plainTextDocumentReaderAndWriter = DEFAULT_PLAIN_TEXT_READER;
/**
* Use a bag of all words as a feature. Perhaps this will find some
* words that indicate certain types of entities are present.
*/
public boolean useBagOfWords = false;
/**
* When scoring, count the background symbol stats too. Useful for
* things where the background symbol is particularly meaningful,
* such as truecase.
*/
public boolean evaluateBackground = false;
/**
* Number of experts to be used in Logarithmic Opinion Pool (product of experts) training
* default value is 1
*/
public int numLopExpert = 1;
public transient String initialLopScales = null;
public transient String initialLopWeights = null;
public boolean includeFullCRFInLOP = false;
public boolean backpropLopTraining = false;
public boolean randomLopWeights = false;
public boolean randomLopFeatureSplit = false;
public boolean nonLinearCRF = false;
public boolean secondOrderNonLinear = false;
public int numHiddenUnits = -1;
public boolean useOutputLayer = true;
public boolean useHiddenLayer = true;
public boolean gradientDebug = false;
public boolean checkGradient = false;
public boolean useSigmoid = false;
public boolean skipOutputRegularization = false;
public boolean sparseOutputLayer = false;
public boolean tieOutputLayer = false;
public boolean blockInitialize = false;
public boolean softmaxOutputLayer = false;
/**
* Bisequence CRF parameters
*/
public String loadBisequenceClassifierEn = null;
public String loadBisequenceClassifierCh = null;
public String bisequenceClassifierPropEn = null;
public String bisequenceClassifierPropCh = null;
public String bisequenceTestFileEn = null;
public String bisequenceTestFileCh = null;
public String bisequenceTestOutputEn = null;
public String bisequenceTestOutputCh = null;
public String bisequenceTestAlignmentFile = null;
public String bisequenceAlignmentTestOutput = null;
public int bisequencePriorType = 1;
public String bisequenceAlignmentPriorPenaltyCh = null;
public String bisequenceAlignmentPriorPenaltyEn = null;
public double alignmentPruneThreshold = 0.0;
public double alignmentDecodeThreshold = 0.5;
public boolean factorInAlignmentProb = false;
public boolean useChromaticSampling = false;
public boolean useSequentialScanSampling = false;
public int maxAllowedChromaticSize = 8;
/**
* Whether or not to keep blank sentences when processing. Useful
* for systems such as the segmenter if you want to line up each
* line exactly, including blank lines.
*/
public boolean keepEmptySentences = false;
public boolean useBilingualNERPrior = false;
public int samplingSpeedUpThreshold = -1;
public String entityMatrixCh = null;
public String entityMatrixEn = null;
public int multiThreadGibbs = 0;
public boolean matchNERIncentive = false;
public boolean useEmbedding = false;
public boolean prependEmbedding = false;
public String embeddingWords = null;
public String embeddingVectors = null;
public boolean transitionEdgeOnly = false;
// L1-prior used in QNMinimizer's OWLQN
public double priorLambda = 0;
public boolean addCapitalFeatures = false;
public int arbitraryInputLayerSize = -1;
public boolean noEdgeFeature = false;
public boolean terminateOnEvalImprovement = false;
public int terminateOnEvalImprovementNumOfEpoch = 1;
public boolean useMemoryEvaluator = true;
public boolean suppressTestDebug = false;
public boolean useOWLQN = false;
public boolean printWeights = false;
public int totalDataSlice = 10;
public int numOfSlices = 0;
public boolean regularizeSoftmaxTieParam = false;
public double softmaxTieLambda = 0;
public int totalFeatureSlice = 10;
public int numOfFeatureSlices = 0;
public boolean addBiasToEmbedding = false;
public boolean hardcodeSoftmaxOutputWeights = false;
public boolean useNERPriorBIO = false; // todo [cdm 2014]: Disused, to be deleted, use priorModelFactory
public String entityMatrix = null;
public int multiThreadClassifier = 0;
public boolean useDualDecomp = false;
public boolean biAlignmentPriorIsPMI = true;
public boolean dampDDStepSizeWithAlignmentProb = false;
public boolean dualDecompAlignment = false;
public double dualDecompInitialStepSizeAlignment = 0.1;
public boolean dualDecompNotBIO = false;
public String berkeleyAlignerLoadPath = null;
public boolean useBerkeleyAlignerForViterbi = false;
public boolean useBerkeleyCompetitivePosterior = false;
public boolean useDenero = true;
public double alignDDAlpha = 1;
public boolean factorInBiEdgePotential = false;
public boolean noNeighborConstraints = false;
public boolean includeC2EViterbi = true;
public boolean initWithPosterior = true;
public int nerSkipFirstK = 0;
public int nerSlowerTimes = 1;
public boolean powerAlignProb = false;
public boolean powerAlignProbAsAddition = false;
public boolean initWithNERPosterior = false;
public boolean applyNERPenalty = true;
public boolean printFactorTable = false;
public boolean useAdaGradFOBOS = false;
public double initRate = 0.1;
public boolean groupByFeatureTemplate = false;
public boolean groupByOutputClass = false;
public double priorAlpha = 0;
public String splitWordRegex = null;
public boolean groupByInput = false;
public boolean groupByHiddenUnit = false;
public String unigramLM = null;
public String bigramLM = null;
public int wordSegBeamSize = 1000;
public String vocabFile = null;
public String normalizedFile = null;
public boolean averagePerceptron = true;
public String loadCRFSegmenterPath = null;
public String loadPCTSegmenterPath = null;
public String crfSegmenterProp = null;
public String pctSegmenterProp = null;
public String intermediateSegmenterOut = null;
public String intermediateSegmenterModel = null;
public int dualDecompMaxItr = 0;
public double dualDecompInitialStepSize = 0.1;
public boolean dualDecompDebug = false;
public boolean useCWSWordFeatures = false;
public boolean useCWSWordFeaturesAll = false;
public boolean useCWSWordFeaturesBigram = false;
public boolean pctSegmenterLenAdjust = false;
public boolean useTrainLexicon = false;
public boolean useCWSFeatures = true;
public boolean appendLC = false;
public boolean perceptronDebug = false;
public boolean pctSegmenterScaleByCRF = false;
public double pctSegmenterScale = 0.0;
public boolean separateASCIIandRange = true;
public double dropoutRate = 0.0;
public double dropoutScale = 1.0;
// keenon: changed from = 1, nowadays it makes sense to default to parallelism
public int multiThreadGrad = Runtime.getRuntime().availableProcessors();
public int maxQNItr = 0;
public boolean dropoutApprox = false;
public String unsupDropoutFile = null;
public double unsupDropoutScale = 1.0;
public int startEvaluateIters = 0;
public int multiThreadPerceptron = 1;
public boolean lazyUpdate = false;
public int featureCountThresh = 0;
public transient String serializeWeightsTo = null;
public boolean geDebug = false;
public boolean doFeatureDiscovery = false;
public transient String loadWeightsFrom = null;
public transient String loadClassIndexFrom = null;
public transient String serializeClassIndexTo = null;
public boolean learnCHBasedOnEN = true;
public boolean learnENBasedOnCH = false;
public String loadWeightsFromEN = null;
public String loadWeightsFromCH = null;
public String serializeToEN = null;
public String serializeToCH = null;
public String testFileEN = null;
public String testFileCH = null;
public String unsupFileEN = null;
public String unsupFileCH = null;
public String unsupAlignFile = null;
public String supFileEN = null;
public String supFileCH = null;
public transient String serializeFeatureIndexTo = null;
public transient String serializeFeatureIndexToText = null;
public String loadFeatureIndexFromEN = null;
public String loadFeatureIndexFromCH = null;
public double lambdaEN = 1.0;
public double lambdaCH = 1.0;
public boolean alternateTraining = false;
public boolean weightByEntropy = false;
public boolean useKL = false;
public boolean useHardGE = false;
public boolean useCRFforUnsup = false;
public boolean useGEforSup = false;
public boolean useKnownLCWords = true; // disused, can be deleted when breaking serialization
// allow for multiple feature factories.
public String[] featureFactories = null;
public List<Object[]> featureFactoriesArgs = null;
public boolean useNoisyLabel = false;
public String errorMatrix = null;
public boolean printTrainLabels = false;
// Inference label dictionary cutoff
public int labelDictionaryCutoff = -1;
public boolean useAdaDelta = false;
public boolean useAdaDiff = false;
public double adaGradEps = 1e-3;
public double adaDeltaRho = 0.95;
public boolean useRandomSeed = false;
public boolean terminateOnAvgImprovement = false;
public boolean strictGoodCoNLL = false;
public boolean removeStrictGoodCoNLLDuplicates = false;
/** A class name for a factory that vends a prior NER model that
* implements both SequenceModel and SequenceListener, and which
* is used in the Gibbs sampling sequence model inference.
*/
public String priorModelFactory;
/** Put in undirected (left/right) bag of words features for local
* neighborhood. Seems much worse than regular useDisjunctive.
*/
public boolean useUndirectedDisjunctive;
public boolean splitSlashHyphenWords; // unused with new enum below. Remove when breaking serialization.
/** How many words it is okay to add to knownLCWords after initial training.
* If this number is negative, then add any number of further words during classifying/testing.
* If this number is non-negative (greater than or equal to 0), then add at most this many words
* to the knownLCWords. By default, this is now set to 0, so there is no transductive learning on the
* test set, since too many people complained about results changing over runs. However, traditionally
* we used a non-zero value, and this usually helps performance a bit (until 2014 it was -1, then it
* was set to 10_000, so that memory would not grow without bound if a SequenceClassifier is run for
* a long time.
*/
public int maxAdditionalKnownLCWords = 0; // was 10_000;
public enum SlashHyphenEnum { NONE, WFRAG, WORD, BOTH };
public SlashHyphenEnum slashHyphenTreatment = SlashHyphenEnum.NONE;
public boolean useTitle2 = false;
public boolean showNCCInfo;
public boolean showCCInfo;
public String crfToExamine;
public boolean useSUTime;
public boolean applyNumericClassifiers;
public String combinationMode;
public String nerModel;
/**
* Use prefixes and suffixes from the previous and next word in node clique.
*/
public boolean useMoreNeighborNGrams = false;
/** if using dict2 in a segmenter, load it with this filename */
public String dict2name = "";
// "ADD VARIABLES ABOVE HERE"
public transient List<String> phraseGazettes = null;
public transient Properties props = null;
/**
* Create a new SeqClassifierFlags object initialized with default values.
*/
public SeqClassifierFlags() { }
/**
* Create a new SeqClassifierFlags object and initialize it using values in
* the Properties object. The properties are printed to stderr as it works.
*
* @param props The properties object used for initialization
*/
public SeqClassifierFlags(Properties props) {
setProperties(props, true);
}
/**
* Create a new SeqClassifierFlags object and initialize it using values in
* the Properties object. The properties are printed to stderr as it works.
*
* @param props The properties object used for initialization
* @param printProps Whether to print the properties on construction
*/
public SeqClassifierFlags(Properties props, boolean printProps) {
setProperties(props, printProps);
}
/**
* Initialize this object using values in Properties object. The properties
* are printed to stderr as it works.
*
* @param props The properties object used for initialization
*/
public final void setProperties(Properties props) {
setProperties(props, true);
}
/**
* Initialize using values in Properties file.
*
* @param props The properties object used for initialization
* @param printProps Whether to print the properties to stderr as it works.
*/
public void setProperties(Properties props, boolean printProps) {
this.props = props;
StringBuilder sb = new StringBuilder(stringRep);
for (String key : props.stringPropertyNames()) {
String val = props.getProperty(key);
if (!(key.isEmpty() && val.isEmpty())) {
if (printProps) {
log.info(key + '=' + val);
}
sb.append(key).append('=').append(val).append('\n');
}
if (key.equalsIgnoreCase("macro")) {
if (Boolean.parseBoolean(val)) {
useObservedSequencesOnly = true;
readerAndWriter = "edu.stanford.nlp.sequences.CoNLLDocumentReaderAndWriter";
// useClassFeature = true;
// submit
useLongSequences = true;
useTaggySequences = true;
useNGrams = true;
usePrev = true;
useNext = true;
useTags = true;
useWordPairs = true;
useSequences = true;
usePrevSequences = true;
// noMidNGrams
noMidNGrams = true;
// reverse
useReverse = true;
// typeseqs3
useTypeSeqs = true;
useTypeSeqs2 = true;
useTypeySequences = true;
// wordtypes2 && known
wordShape = WordShapeClassifier.WORDSHAPEDAN2USELC;
// occurrence
useOccurrencePatterns = true;
// realword
useLastRealWord = true;
useNextRealWord = true;
// smooth
sigma = 3.0;
// normalize
normalize = true;
normalizeTimex = true;
}
} else if (key.equalsIgnoreCase("goodCoNLL")) {
// This was developed for CMMClassifier after the original 2003 CoNLL work.
// It is for an MEMM. You shouldn't use it with CRFClassifier.
if (Boolean.parseBoolean(val)) {
// featureFactory = "edu.stanford.nlp.ie.NERFeatureFactory";
readerAndWriter = "edu.stanford.nlp.sequences.CoNLLDocumentReaderAndWriter";
useObservedSequencesOnly = true;
// useClassFeature = true;
useLongSequences = true;
useTaggySequences = true;
useNGrams = true;
usePrev = true;
useNext = true;
useTags = true;
useWordPairs = true;
useSequences = true;
usePrevSequences = true;
// noMidNGrams
noMidNGrams = true;
// should this be set?? maxNGramLeng = 6; No (to get best score).
// reverse
useReverse = false;
// typeseqs3
useTypeSeqs = true;
useTypeSeqs2 = true;
useTypeySequences = true;
// wordtypes2 && known
wordShape = WordShapeClassifier.WORDSHAPEDAN2USELC;
// occurrence
useOccurrencePatterns = true;
// realword
useLastRealWord = true;
useNextRealWord = true;
// smooth
// This was originally 20, but in Aug 2006 increased to 50, because that helped
// for English, but actually even smaller than 20 helps for languages like
// Spanish, so dropped in 2014 to 5.0.
sigma = 5.0;
// normalize
normalize = true;
normalizeTimex = true; // this was sort of wrong for German since it lowercases months, but didn't do too much harm
maxLeft = 2;
useDisjunctive = true;
disjunctionWidth = 4; // clearly optimal for CoNLL
useBoundarySequences = true;
useLemmas = true; // no-op except for German
usePrevNextLemmas = true; // no-op except for German
strictGoodCoNLL = true; // don't add some CpC features added later
removeStrictGoodCoNLLDuplicates = true; // added in 2014; the duplicated features don't help
inputEncoding = "iso-8859-1"; // needed for CoNLL German and Spanish files
// optimization
useQN = true;
QNsize = 15;
}
} else if (key.equalsIgnoreCase("conllNoTags")) {
if (Boolean.parseBoolean(val)) {
readerAndWriter = "edu.stanford.nlp.sequences.ColumnDocumentReaderAndWriter";
// trainMap=testMap="word=0,answer=1";
map = "word=0,answer=1";
useObservedSequencesOnly = true;
// useClassFeature = true;
useLongSequences = true;
// useTaggySequences = true;
useNGrams = true;
usePrev = true;
useNext = true;
// useTags = true;
useWordPairs = true;
useSequences = true;
usePrevSequences = true;
// noMidNGrams
noMidNGrams = true;
// reverse
useReverse = false;
// typeseqs3
useTypeSeqs = true;
useTypeSeqs2 = true;
useTypeySequences = true;
// wordtypes2 && known
wordShape = WordShapeClassifier.WORDSHAPEDAN2USELC;
// occurrence
// useOccurrencePatterns = true;
// realword
useLastRealWord = true;
useNextRealWord = true;
// smooth
sigma = 20.0;
adaptSigma = 20.0;
// normalize
normalize = true;
normalizeTimex = true;
maxLeft = 2;
useDisjunctive = true;
disjunctionWidth = 4;
useBoundarySequences = true;
// useLemmas = true; // no-op except for German
// usePrevNextLemmas = true; // no-op except for German
inputEncoding = "iso-8859-1";
// opt
useQN = true;
QNsize = 15;
}
} else if (key.equalsIgnoreCase("notags")) {
if (Boolean.parseBoolean(val)) {
// turn off all features that use POS tags
// this is slightly crude: it also turns off a few things that
// don't use tags in e.g., useTaggySequences
useTags = false;
useSymTags = false;
useTaggySequences = false;
useOccurrencePatterns = false;
}
} else if (key.equalsIgnoreCase("submit")) {
if (Boolean.parseBoolean(val)) {
useLongSequences = true;
useTaggySequences = true;
useNGrams = true;
usePrev = true;
useNext = true;
useTags = true;
useWordPairs = true;
wordShape = WordShapeClassifier.WORDSHAPEDAN1;
useSequences = true;
usePrevSequences = true;
}
} else if (key.equalsIgnoreCase("binnedLengths")) {
if (val != null) {
String[] binnedLengthStrs = val.split("[, ]+");
binnedLengths = new int[binnedLengthStrs.length];
for (int i = 0; i < binnedLengths.length; i++) {
binnedLengths[i] = Integer.parseInt(binnedLengthStrs[i]);
}
}
} else if (key.equalsIgnoreCase("makeConsistent")) {
makeConsistent = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("dump")) {
dump = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNGrams")) {
useNGrams = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNeighborNGrams")) {
useNeighborNGrams = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useMoreNeighborNGrams")) {
useMoreNeighborNGrams = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("wordFunction")) {
wordFunction = ReflectionLoading.loadByReflection(val);
} else if (key.equalsIgnoreCase("conjoinShapeNGrams")) {
conjoinShapeNGrams = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("lowercaseNGrams")) {
lowercaseNGrams = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useIsURL")) {
useIsURL = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useURLSequences")) {
useURLSequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useEntityTypes")) {
useEntityTypes = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useEntityRule")) {
useEntityRule = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useOrdinal")) {
useOrdinal = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useEntityTypeSequences")) {
useEntityTypeSequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useIsDateRange")) {
useIsDateRange = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("dehyphenateNGrams")) {
dehyphenateNGrams = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("lowerNewgeneThreshold")) {
lowerNewgeneThreshold = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePrev")) {
usePrev = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNext")) {
useNext = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTags")) {
useTags = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWordPairs")) {
useWordPairs = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useGazettes")) {
useGazettes = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("wordShape")) {
wordShape = WordShapeClassifier.lookupShaper(val);
if (wordShape == WordShapeClassifier.NOWORDSHAPE) {
log.warn("There is no word shaper called '" + val + "'; no word shape features will be used.");
}
} else if (key.equalsIgnoreCase("useShapeStrings")) {
useShapeStrings = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useGoodForNamesCpC")) {
useGoodForNamesCpC = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useDictionaryConjunctions")) {
useDictionaryConjunctions = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useDictionaryConjunctions3")) {
useDictionaryConjunctions3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("expandMidDot")) {
expandMidDot = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useSequences")) {
useSequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePrevSequences")) {
usePrevSequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNextSequences")) {
useNextSequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useLongSequences")) {
useLongSequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useBoundarySequences")) {
useBoundarySequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTaggySequences")) {
useTaggySequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useExtraTaggySequences")) {
useExtraTaggySequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTaggySequencesShapeInteraction")) {
useTaggySequencesShapeInteraction = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("strictlyZeroethOrder")) {
strictlyZeroethOrder = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("strictlyFirstOrder")) {
strictlyFirstOrder = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("strictlySecondOrder")) {
strictlySecondOrder = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("strictlyThirdOrder")) {
strictlyThirdOrder = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("dontExtendTaggy")) {
dontExtendTaggy = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("entitySubclassification")) {
entitySubclassification = val;
} else if (key.equalsIgnoreCase("useGazettePhrases")) {
useGazettePhrases = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("phraseGazettes")) {
StringTokenizer st = new StringTokenizer(val, " ,;\t");
if (phraseGazettes == null) {
phraseGazettes = new ArrayList<>();
}
while (st.hasMoreTokens()) {
phraseGazettes.add(st.nextToken());
}
} else if (key.equalsIgnoreCase("useSum")) {
useSum = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("verbose")) {
verboseMode = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("verboseMode")) {
verboseMode = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("tolerance")) {
tolerance = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("maxIterations")) {
maxIterations = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("exportFeatures")) {
exportFeatures = val;
} else if (key.equalsIgnoreCase("printFeatures")) {
printFeatures = val;
} else if (key.equalsIgnoreCase("printFeaturesUpto")) {
printFeaturesUpto = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("lastNameList")) {
lastNameList = val;
} else if (key.equalsIgnoreCase("maleNameList")) {
maleNameList = val;
} else if (key.equalsIgnoreCase("femaleNameList")) {
femaleNameList = val;
} else if (key.equalsIgnoreCase("useSymTags")) {
useSymTags = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useSymWordPairs")) {
useSymWordPairs = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("printClassifier")) {
printClassifier = val;
} else if (key.equalsIgnoreCase("printClassifierParam")) {
printClassifierParam = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("intern")) {
intern = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("mergetags")) {
mergeTags = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("iobTags")) {
iobTags = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useViterbi")) {
useViterbi = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("intern2")) {
intern2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("selfTest")) {
selfTest = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("sloppyGazette")) {
sloppyGazette = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("cleanGazette")) {
cleanGazette = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("noMidNGrams")) {
noMidNGrams = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useReverse")) {
useReverse = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("retainEntitySubclassification")) {
retainEntitySubclassification = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useLemmas")) {
useLemmas = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePrevNextLemmas")) {
usePrevNextLemmas = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("normalizeTerms")) {
normalizeTerms = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("normalizeTimex")) {
normalizeTimex = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNB")) {
useNB = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useParenMatching")) {
useParenMatching = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTypeSeqs")) {
useTypeSeqs = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTypeSeqs2")) {
useTypeSeqs2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTypeSeqs3")) {
useTypeSeqs3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useDisjunctive")) {
useDisjunctive = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useUndirectedDisjunctive")) {
useUndirectedDisjunctive = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("splitSlashHyphenWords")) {
try {
slashHyphenTreatment = SlashHyphenEnum.valueOf(val.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException | NullPointerException iae) {
slashHyphenTreatment = SlashHyphenEnum.NONE;
}
} else if (key.equalsIgnoreCase("disjunctionWidth")) {
disjunctionWidth = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useDisjunctiveShapeInteraction")) {
useDisjunctiveShapeInteraction = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWideDisjunctive")) {
useWideDisjunctive = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("wideDisjunctionWidth")) {
wideDisjunctionWidth = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useDisjShape")) {
useDisjShape = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTitle")) {
useTitle = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTitle2")) {
useTitle2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("booleanFeatures")) {
booleanFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useClassFeature")) {
useClassFeature = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useShapeConjunctions")) {
useShapeConjunctions = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWordTag")) {
useWordTag = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNPHead")) {
useNPHead = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNPGovernor")) {
useNPGovernor = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useHeadGov")) {
useHeadGov = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useLastRealWord")) {
useLastRealWord = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNextRealWord")) {
useNextRealWord = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useOccurrencePatterns")) {
useOccurrencePatterns = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTypeySequences")) {
useTypeySequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("justify")) {
justify = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("normalize")) {
normalize = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("priorType")) {
priorType = val;
} else if (key.equalsIgnoreCase("sigma")) {
sigma = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("epsilon")) {
epsilon = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("beamSize")) {
beamSize = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("removeTopN")) {
removeTopN = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("removeTopNPercent")) {
removeTopNPercent = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("randomizedRatio")) {
randomizedRatio = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("numTimesRemoveTopN")) {
numTimesRemoveTopN = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("maxLeft")) {
maxLeft = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("maxRight")) {
maxRight = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("maxNGramLeng")) {
maxNGramLeng = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useGazFeatures")) {
useGazFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAltGazFeatures")) {
useAltGazFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useMoreGazFeatures")) {
useMoreGazFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAbbr")) {
useAbbr = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useMinimalAbbr")) {
useMinimalAbbr = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAbbr1")) {
useAbbr1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useMinimalAbbr1")) {
useMinimalAbbr1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("documentReader")) {
log.info("You are using an outdated flag: -documentReader " + val);
log.info("Please use -readerAndWriter instead.");
} else if (key.equalsIgnoreCase("deleteBlankLines")) {
deleteBlankLines = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("answerFile")) {
answerFile = val;
} else if (key.equalsIgnoreCase("altAnswerFile")) {
altAnswerFile = val;
} else if (key.equalsIgnoreCase("loadClassifier") ||
key.equalsIgnoreCase("model")) {
loadClassifier = val;
} else if (key.equalsIgnoreCase("loadTextClassifier")) {
loadTextClassifier = val;
} else if (key.equalsIgnoreCase("loadJarClassifier")) {
loadJarClassifier = val;
} else if (key.equalsIgnoreCase("loadAuxClassifier")) {
loadAuxClassifier = val;
} else if (key.equalsIgnoreCase("serializeTo")) {
serializeTo = val;
} else if (key.equalsIgnoreCase("serializeToText")) {
serializeToText = val;
} else if (key.equalsIgnoreCase("serializeDatasetsDir")) {
serializeDatasetsDir = val;
} else if (key.equalsIgnoreCase("loadDatasetsDir")) {
loadDatasetsDir = val;
} else if (key.equalsIgnoreCase("pushDir")) {
pushDir = val;
} else if (key.equalsIgnoreCase("purgeDatasets")) {
purgeDatasets = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("keepOBInMemory")) {
keepOBInMemory = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("fakeDataset")) {
fakeDataset = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("numDatasetsPerFile")) {
numDatasetsPerFile = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("trainFile")) {
trainFile = val;
} else if (key.equalsIgnoreCase("biasedTrainFile")) {
biasedTrainFile = val;
} else if (key.equalsIgnoreCase("classBias")) {
classBias = val;
} else if (key.equalsIgnoreCase("confusionMatrix")) {
confusionMatrix = val;
} else if (key.equalsIgnoreCase("adaptFile")) {
adaptFile = val;
} else if (key.equalsIgnoreCase("devFile")) {
devFile = val;
} else if (key.equalsIgnoreCase("testFile")) {
testFile = val;
} else if (key.equalsIgnoreCase("outputFile")) {
outputFile = val;
} else if (key.equalsIgnoreCase("textFile")) {
textFile = val;
} else if (key.equalsIgnoreCase("readStdin")) {
readStdin = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("initialWeights")) {
initialWeights = val;
} else if (key.equalsIgnoreCase("interimOutputFreq")) {
interimOutputFreq = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("inputEncoding")) {
inputEncoding = val;
} else if (key.equalsIgnoreCase("outputEncoding")) {
outputEncoding = val;
} else if (key.equalsIgnoreCase("encoding")) {
inputEncoding = val;
outputEncoding = val;
} else if (key.equalsIgnoreCase("gazette")) {
useGazettes = true;
StringTokenizer st = new StringTokenizer(val, " ,;\t");
if (gazettes == null) {
gazettes = new ArrayList<>();
} // for after deserialization, as gazettes is transient
while (st.hasMoreTokens()) {
gazettes.add(st.nextToken());
}
} else if (key.equalsIgnoreCase("useQN")) {
useQN = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("QNsize")) {
QNsize = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("QNsize2")) {
QNsize2 = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("l1reg")) {
useQN = false;
l1reg = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("useFloat")) {
useFloat = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("trainMap")) {
log.info("trainMap and testMap are no longer valid options - please use map instead.");
throw new RuntimeException();
} else if (key.equalsIgnoreCase("testMap")) {
log.info("trainMap and testMap are no longer valid options - please use map instead.");
throw new RuntimeException();
} else if (key.equalsIgnoreCase("map")) {
map = val;
} else if (key.equalsIgnoreCase("useMoreAbbr")) {
useMoreAbbr = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePrevVB")) {
usePrevVB = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNextVB")) {
useNextVB = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useVB")) {
if (Boolean.parseBoolean(val)) {
useVB = true;
usePrevVB = true;
useNextVB = true;
}
} else if (key.equalsIgnoreCase("useChunks")) {
useChunks = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useChunkySequences")) {
useChunkySequences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("greekifyNGrams")) {
greekifyNGrams = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("restrictTransitionsTimit")) {
restrictTransitionsTimit = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useMoreTags")) {
useMoreTags = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useBeginSent")) {
useBeginSent = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePosition")) {
usePosition = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useGenia")) {
useGENIA = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAbstr")) {
useABSTR = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWeb")) {
useWEB = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAnte")) {
useANTE = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAcr")) {
useACR = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTok")) {
useTOK = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAbgene")) {
useABGENE = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAbstrFreqDict")) {
useABSTRFreqDict = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAbstrFreq")) {
useABSTRFreq = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useFreq")) {
useFREQ = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usewebfreqdict")) {
useWEBFreqDict = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("bioSubmitOutput")) {
bioSubmitOutput = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("subCWGaz")) {
subCWGaz = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("splitOnHead")) {
splitOnHead = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("featureCountThreshold")) {
featureCountThreshold = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useWord")) {
useWord = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("memoryThrift")) {
memoryThrift = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("timitDatum")) {
timitDatum = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("splitDocuments")) {
log.info("You are using an outdated flag: -splitDocuments");
log.info("Please use -maxDocSize -1 instead.");
splitDocuments = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("featureWeightThreshold")) {
featureWeightThreshold = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("backgroundSymbol")) {
backgroundSymbol = val;
} else if (key.equalsIgnoreCase("featureFactory")) {
// handle multiple feature factories.
String[] tokens = val.split("\\s*,\\s*"); // multiple feature factories could be specified and are comma separated.
int numFactories = tokens.length;
if (numFactories==1){ // for compatible reason
featureFactory = getFeatureFactory(val);
}
featureFactories = new String[numFactories];
featureFactoriesArgs = new ArrayList<>(numFactories);
for (int i = 0; i < numFactories; i++) {
featureFactories[i] = getFeatureFactory(tokens[i]);
featureFactoriesArgs.add(new Object[0]);
}
} else if (key.equalsIgnoreCase("printXML")) {
log.info("printXML is disused; perhaps try using the -outputFormat xml option.");
} else if (key.equalsIgnoreCase("useSeenFeaturesOnly")) {
useSeenFeaturesOnly = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useBagOfWords")) {
useBagOfWords = Boolean.parseBoolean(val);
// chinese word-segmenter features
} else if (key.equalsIgnoreCase("useRadical")) {
useRadical = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useBigramInTwoClique")) {
useBigramInTwoClique = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useReverseAffix")) {
useReverseAffix = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("charHalfWindow")) {
charHalfWindow = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("purgeFeatures")) {
purgeFeatures = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("ocrFold")) {
ocrFold = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("morphFeatureFile")) {
morphFeatureFile = val;
} else if (key.equalsIgnoreCase("svmModelFile")) {
svmModelFile = val;
/* Dictionary */
} else if (key.equalsIgnoreCase("useDictleng")) {
useDictleng = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useDict2")) {
useDict2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useOutDict2")) {
useOutDict2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("outDict2")) {
outDict2 = val;
} else if (key.equalsIgnoreCase("useDictCTB2")) {
useDictCTB2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useDictASBC2")) {
useDictASBC2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useDictPK2")) {
useDictPK2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useDictHK2")) {
useDictHK2 = Boolean.parseBoolean(val);
/* N-gram flags */
} else if (key.equalsIgnoreCase("useWord1")) {
useWord1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWord2")) {
useWord2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWord3")) {
useWord3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWord4")) {
useWord4 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useRad1")) {
useRad1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useRad2")) {
useRad2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useRad2b")) {
useRad2b = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWordn")) {
useWordn = Boolean.parseBoolean(val);
/* affix flags */
} else if (key.equalsIgnoreCase("useCTBPre1")) {
useCTBPre1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useCTBSuf1")) {
useCTBSuf1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useASBCPre1")) {
useASBCPre1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useASBCSuf1")) {
useASBCSuf1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useHKPre1")) {
useHKPre1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useHKSuf1")) {
useHKSuf1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePKPre1")) {
usePKPre1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePKSuf1")) {
usePKSuf1 = Boolean.parseBoolean(val);
/* POS flags */
} else if (key.equalsIgnoreCase("useCTBChar2")) {
useCTBChar2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePrediction")) {
usePrediction = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useASBCChar2")) {
useASBCChar2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useHKChar2")) {
useHKChar2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePKChar2")) {
usePKChar2 = Boolean.parseBoolean(val);
/* Rule flag */
} else if (key.equalsIgnoreCase("useRule2")) {
useRule2 = Boolean.parseBoolean(val);
/* ASBC and HK */
} else if (key.equalsIgnoreCase("useBig5")) {
useBig5 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegDict2")) {
useNegDict2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegDict3")) {
useNegDict3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegDict4")) {
useNegDict4 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegCTBDict2")) {
useNegCTBDict2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegCTBDict3")) {
useNegCTBDict3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegCTBDict4")) {
useNegCTBDict4 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegASBCDict2")) {
useNegASBCDict2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegASBCDict3")) {
useNegASBCDict3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegASBCDict4")) {
useNegASBCDict4 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegPKDict2")) {
useNegPKDict2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegPKDict3")) {
useNegPKDict3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegPKDict4")) {
useNegPKDict4 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegHKDict2")) {
useNegHKDict2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegHKDict3")) {
useNegHKDict3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNegHKDict4")) {
useNegHKDict4 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePre")) {
usePre = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useSuf")) {
useSuf = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useRule")) {
useRule = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAs")) {
useAs = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePk")) {
usePk = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useHk")) {
useHk = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useMsr")) {
useMsr = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useMSRChar2")) {
useMSRChar2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useFeaturesC4gram")) {
useFeaturesC4gram = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useFeaturesC5gram")) {
useFeaturesC5gram = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useFeaturesC6gram")) {
useFeaturesC6gram = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useFeaturesCpC4gram")) {
useFeaturesCpC4gram = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useFeaturesCpC5gram")) {
useFeaturesCpC5gram = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useFeaturesCpC6gram")) {
useFeaturesCpC6gram = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useUnicodeType")) {
useUnicodeType = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useUnicodeBlock")) {
useUnicodeBlock = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useUnicodeType4gram")) {
useUnicodeType4gram = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useUnicodeType5gram")) {
useUnicodeType5gram = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useShapeStrings1")) {
useShapeStrings1 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useShapeStrings3")) {
useShapeStrings3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useShapeStrings4")) {
useShapeStrings4 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useShapeStrings5")) {
useShapeStrings5 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWordUTypeConjunctions2")) {
useWordUTypeConjunctions2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWordUTypeConjunctions3")) {
useWordUTypeConjunctions3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWordShapeConjunctions2")) {
useWordShapeConjunctions2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWordShapeConjunctions3")) {
useWordShapeConjunctions3 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useMidDotShape")) {
useMidDotShape = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("augmentedDateChars")) {
augmentedDateChars = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("suppressMidDotPostprocessing")) {
suppressMidDotPostprocessing = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("printNR")) {
printNR = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("use4Clique")) {
use4Clique = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useFilter")) {
useFilter = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("largeChSegFile")) {
largeChSegFile = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("keepEnglishWhitespaces")) {
keepEnglishWhitespaces = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("keepAllWhitespaces")) {
keepAllWhitespaces = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("sighanPostProcessing")) {
sighanPostProcessing = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useChPos")) {
useChPos = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("sighanCorporaDict")) {
sighanCorporaDict = val;
// end chinese word-segmenter features
} else if (key.equalsIgnoreCase("useObservedSequencesOnly")) {
useObservedSequencesOnly = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("maxDocSize")) {
maxDocSize = Integer.parseInt(val);
splitDocuments = true;
} else if (key.equalsIgnoreCase("printProbs")) {
printProbs = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("printFirstOrderProbs")) {
printFirstOrderProbs = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("saveFeatureIndexToDisk")) {
saveFeatureIndexToDisk = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("removeBackgroundSingletonFeatures")) {
removeBackgroundSingletonFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("doGibbs")) {
doGibbs = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useMUCFeatures")) {
useMUCFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("initViterbi")) {
initViterbi = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("checkNameList")) {
checkNameList = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useFirstWord")) {
useFirstWord = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useUnknown")) {
useUnknown = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("cacheNGrams")) {
cacheNGrams = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useNumberFeature")) {
useNumberFeature = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("annealingRate")) {
annealingRate = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("annealingType")) {
if (val.equalsIgnoreCase("linear") || val.equalsIgnoreCase("exp") || val.equalsIgnoreCase("exponential")) {
annealingType = val;
} else {
log.info("unknown annealingType: " + val + ". Please use linear|exp|exponential");
}
} else if (key.equalsIgnoreCase("numSamples")) {
numSamples = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("inferenceType")) {
inferenceType = val;
} else if (key.equalsIgnoreCase("loadProcessedData")) {
loadProcessedData = val;
} else if (key.equalsIgnoreCase("normalizationTable")) {
normalizationTable = val;
} else if (key.equalsIgnoreCase("dictionary")) {
// don't set if empty string or spaces or true: revert it to null
// special case so can empty out dictionary list on command line!
val = val.trim();
if (val.length() > 0 && !"true".equals(val) && !"null".equals(val) && !"false".equals("val")) {
dictionary = val;
} else {
dictionary = null;
}
} else if (key.equalsIgnoreCase("serDictionary")) {
// don't set if empty string or spaces or true: revert it to null
// special case so can empty out dictionary list on command line!
val = val.trim();
if (val.length() > 0 && !"true".equals(val) && !"null".equals(val) && !"false".equals("val")) {
serializedDictionary = val;
} else {
serializedDictionary = null;
}
} else if (key.equalsIgnoreCase("dictionary2")) {
// don't set if empty string or spaces or true: revert it to null
// special case so can empty out dictionary list on command line!
val = val.trim();
if (val.length() > 0 && !"true".equals(val) && !"null".equals(val) && !"false".equals("val")) {
dictionary2 = val;
} else {
dictionary2 = null;
}
} else if (key.equalsIgnoreCase("normTableEncoding")) {
normTableEncoding = val;
} else if (key.equalsIgnoreCase("useLemmaAsWord")) {
useLemmaAsWord = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("type")) {
type = val;
} else if (key.equalsIgnoreCase("readerAndWriter")) {
readerAndWriter = val;
} else if (key.equalsIgnoreCase("plainTextDocumentReaderAndWriter")) {
plainTextDocumentReaderAndWriter = val;
} else if (key.equalsIgnoreCase("gazFilesFile")) {
gazFilesFile = val;
} else if (key.equalsIgnoreCase("baseTrainDir")) {
baseTrainDir = val;
} else if (key.equalsIgnoreCase("baseTestDir")) {
baseTestDir = val;
} else if (key.equalsIgnoreCase("trainFiles")) {
trainFiles = val;
} else if (key.equalsIgnoreCase("trainFileList")) {
trainFileList = val;
} else if (key.equalsIgnoreCase("trainDirs")) {
trainDirs = val;
} else if (key.equalsIgnoreCase("testDirs")) {
testDirs = val;
} else if (key.equalsIgnoreCase("testFiles")) {
testFiles = val;
} else if (key.equalsIgnoreCase("textFiles")) {
textFiles = val;
} else if (key.equalsIgnoreCase("usePrediction2")) {
usePrediction2 = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useObservedFeaturesOnly")) {
useObservedFeaturesOnly = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("iobWrapper")) {
iobWrapper = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useDistSim")) {
useDistSim = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("casedDistSim")) {
casedDistSim = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("distSimFileFormat")) {
distSimFileFormat = val;
} else if (key.equalsIgnoreCase("distSimMaxBits")) {
distSimMaxBits = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("numberEquivalenceDistSim")) {
numberEquivalenceDistSim = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("unknownWordDistSimClass")) {
unknownWordDistSimClass = val;
} else if (key.equalsIgnoreCase("useOnlySeenWeights")) {
useOnlySeenWeights = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("predProp")) {
predProp = val;
} else if (key.equalsIgnoreCase("distSimLexicon")) {
distSimLexicon = val;
} else if (key.equalsIgnoreCase("useSegmentation")) {
useSegmentation = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useInternal")) {
useInternal = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useExternal")) {
useExternal = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useEitherSideWord")) {
useEitherSideWord = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useEitherSideDisjunctive")) {
useEitherSideDisjunctive = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("featureDiffThresh")) {
featureDiffThresh = Double.parseDouble(val);
if (props.getProperty("numTimesPruneFeatures") == null) {
numTimesPruneFeatures = 1;
}
} else if (key.equalsIgnoreCase("numTimesPruneFeatures")) {
numTimesPruneFeatures = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("newgeneThreshold")) {
newgeneThreshold = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("adaptFile")) {
adaptFile = val;
} else if (key.equalsIgnoreCase("doAdaptation")) {
doAdaptation = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("selfTrainFile")) {
selfTrainFile = val;
} else if (key.equalsIgnoreCase("selfTrainIterations")) {
selfTrainIterations = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("selfTrainWindowSize")) {
selfTrainWindowSize = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("selfTrainConfidenceThreshold")) {
selfTrainConfidenceThreshold = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("numFolds")) {
numFolds = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("startFold")) {
startFold = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("endFold")) {
endFold = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("adaptSigma")) {
adaptSigma = Double.parseDouble(val);
} else if (key.startsWith("prop") && !key.equals("prop")) {
comboProps.add(val);
} else if (key.equalsIgnoreCase("outputFormat")) {
outputFormat = val;
} else if (key.equalsIgnoreCase("useSMD")) {
useSMD = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useScaledSGD")) {
useScaledSGD = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("scaledSGDMethod")) {
scaledSGDMethod = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("tuneSGD")) {
tuneSGD = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("StochasticCalculateMethod")) {
if (val.equalsIgnoreCase("AlgorithmicDifferentiation")) {
stochasticMethod = StochasticCalculateMethods.AlgorithmicDifferentiation;
} else if (val.equalsIgnoreCase("IncorporatedFiniteDifference")) {
stochasticMethod = StochasticCalculateMethods.IncorporatedFiniteDifference;
} else if (val.equalsIgnoreCase("ExternalFinitedifference")) {
stochasticMethod = StochasticCalculateMethods.ExternalFiniteDifference;
}
} else if (key.equalsIgnoreCase("initialGain")) {
initialGain = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("stochasticBatchSize")) {
stochasticBatchSize = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("SGD2QNhessSamples")) {
SGD2QNhessSamples = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useSGD")) {
useSGD = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useInPlaceSGD")) {
useInPlaceSGD = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useSGDtoQN")) {
useSGDtoQN = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("SGDPasses")) {
SGDPasses = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("QNPasses")) {
QNPasses = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("gainSGD")) {
gainSGD = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("useHybrid")) {
useHybrid = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("hybridCutoffIteration")) {
hybridCutoffIteration = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useStochasticQN")) {
useStochasticQN = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("outputIterationsToFile")) {
outputIterationsToFile = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("testObjFunction")) {
testObjFunction = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("testVariance")) {
testVariance = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("CRForder")) {
CRForder = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("CRFwindow")) {
CRFwindow = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("testHessSamples")) {
testHessSamples = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("estimateInitial")) {
estimateInitial = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("printLabelValue")) {
printLabelValue = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("searchGraphPrefix")) {
searchGraphPrefix = val;
} else if (key.equalsIgnoreCase("searchGraphPrune")) {
searchGraphPrune = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("kBest")) {
useKBest = true;
kBest = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useRobustQN")) {
useRobustQN = true;
} else if (key.equalsIgnoreCase("combo")) {
combo = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("verboseForTrueCasing")) {
verboseForTrueCasing = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("trainHierarchical")) {
trainHierarchical = val;
} else if (key.equalsIgnoreCase("domain")) {
domain = val;
} else if (key.equalsIgnoreCase("baseline")) {
baseline = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("doFE")) {
doFE = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("restrictLabels")) {
restrictLabels = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("transferSigmas")) {
transferSigmas = val;
} else if (key.equalsIgnoreCase("announceObjectBankEntries")) {
announceObjectBankEntries = true;
} else if (key.equalsIgnoreCase("mixedCaseMapFile")) {
mixedCaseMapFile = val;
} else if (key.equalsIgnoreCase("auxTrueCaseModels")) {
auxTrueCaseModels = val;
} else if (key.equalsIgnoreCase("use2W")) {
use2W = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useLC")) {
useLC = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useYetMoreCpCShapes")) {
useYetMoreCpCShapes = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useIfInteger")) {
useIfInteger = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("twoStage")) {
twoStage = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("evaluateIters")) {
evaluateIters = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("evalCmd")) {
evalCmd = val;
} else if (key.equalsIgnoreCase("evaluateTrain")) {
evaluateTrain = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("evaluateBackground")) {
evaluateBackground = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("tuneSampleSize")) {
tuneSampleSize = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useTopics")) {
useTopics = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePhraseFeatures")) {
usePhraseFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePhraseWords")) {
usePhraseWords = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePhraseWordTags")) {
usePhraseWordTags = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("usePhraseWordSpecialTags")) {
usePhraseWordSpecialTags = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useProtoFeatures")) {
useProtoFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useWordnetFeatures")) {
useWordnetFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("wikiFeatureDbFile")) {
wikiFeatureDbFile = val;
} else if (key.equalsIgnoreCase("tokenizerOptions")) {
tokenizerOptions = val;
} else if (key.equalsIgnoreCase("tokenizerFactory")) {
tokenizerFactory = val;
} else if (key.equalsIgnoreCase("useCommonWordsFeature")) {
useCommonWordsFeature = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useYear")) {
useYear = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useSentenceNumber")) {
useSentenceNumber = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useLabelSource")) {
useLabelSource = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("tokenFactory")) {
tokenFactory = val;
} else if (key.equalsIgnoreCase("tokensAnnotationClassName")) {
tokensAnnotationClassName = val;
} else if (key.equalsIgnoreCase("numLopExpert")) {
numLopExpert = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("initialLopScales")) {
initialLopScales = val;
} else if (key.equalsIgnoreCase("initialLopWeights")) {
initialLopWeights = val;
} else if (key.equalsIgnoreCase("includeFullCRFInLOP")) {
includeFullCRFInLOP = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("backpropLopTraining")) {
backpropLopTraining = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("randomLopWeights")) {
randomLopWeights = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("randomLopFeatureSplit")) {
randomLopFeatureSplit = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("nonLinearCRF")) {
nonLinearCRF = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("secondOrderNonLinear")) {
secondOrderNonLinear = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("numHiddenUnits")) {
numHiddenUnits = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useOutputLayer")) {
useOutputLayer = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useHiddenLayer")) {
useHiddenLayer = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("gradientDebug")) {
gradientDebug = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("checkGradient")) {
checkGradient = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useSigmoid")) {
useSigmoid = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("skipOutputRegularization")) {
skipOutputRegularization = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("sparseOutputLayer")) {
sparseOutputLayer = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("tieOutputLayer")) {
tieOutputLayer = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("blockInitialize")) {
blockInitialize = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("softmaxOutputLayer")) {
softmaxOutputLayer = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("loadBisequenceClassifierEn")) {
loadBisequenceClassifierEn = val;
} else if (key.equalsIgnoreCase("bisequenceClassifierPropEn")) {
bisequenceClassifierPropEn = val;
} else if (key.equalsIgnoreCase("loadBisequenceClassifierCh")) {
loadBisequenceClassifierCh = val;
} else if (key.equalsIgnoreCase("bisequenceClassifierPropCh")) {
bisequenceClassifierPropCh = val;
} else if (key.equalsIgnoreCase("bisequenceTestFileEn")) {
bisequenceTestFileEn = val;
} else if (key.equalsIgnoreCase("bisequenceTestFileCh")) {
bisequenceTestFileCh = val;
} else if (key.equalsIgnoreCase("bisequenceTestOutputEn")) {
bisequenceTestOutputEn = val;
} else if (key.equalsIgnoreCase("bisequenceTestOutputCh")) {
bisequenceTestOutputCh = val;
} else if (key.equalsIgnoreCase("bisequenceTestAlignmentFile")) {
bisequenceTestAlignmentFile = val;
} else if (key.equalsIgnoreCase("bisequenceAlignmentTestOutput")) {
bisequenceAlignmentTestOutput = val;
} else if (key.equalsIgnoreCase("bisequencePriorType")) {
bisequencePriorType = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("bisequenceAlignmentPriorPenaltyCh")) {
bisequenceAlignmentPriorPenaltyCh = val;
} else if (key.equalsIgnoreCase("bisequenceAlignmentPriorPenaltyEn")) {
bisequenceAlignmentPriorPenaltyEn = val;
} else if (key.equalsIgnoreCase("alignmentPruneThreshold")) {
alignmentPruneThreshold = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("alignmentDecodeThreshold")) {
alignmentDecodeThreshold = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("factorInAlignmentProb")) {
factorInAlignmentProb = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useChromaticSampling")) {
useChromaticSampling = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useSequentialScanSampling")) {
useSequentialScanSampling = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("maxAllowedChromaticSize")) {
maxAllowedChromaticSize = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("keepEmptySentences")) {
keepEmptySentences = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useBilingualNERPrior")) {
useBilingualNERPrior = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("samplingSpeedUpThreshold")) {
samplingSpeedUpThreshold = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("entityMatrixCh")) {
entityMatrixCh = val;
} else if (key.equalsIgnoreCase("entityMatrixEn")) {
entityMatrixEn = val;
} else if (key.equalsIgnoreCase("multiThreadGibbs")) {
multiThreadGibbs = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("matchNERIncentive")) {
matchNERIncentive = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useEmbedding")) {
useEmbedding = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("prependEmbedding")) {
prependEmbedding = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("embeddingWords")) {
embeddingWords = val;
} else if (key.equalsIgnoreCase("embeddingVectors")) {
embeddingVectors = val;
} else if (key.equalsIgnoreCase("transitionEdgeOnly")) {
transitionEdgeOnly = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("priorLambda")) {
priorLambda = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("addCapitalFeatures")) {
addCapitalFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("arbitraryInputLayerSize")) {
arbitraryInputLayerSize = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("noEdgeFeature")) {
noEdgeFeature = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("terminateOnEvalImprovement")) {
terminateOnEvalImprovement = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("terminateOnEvalImprovementNumOfEpoch")) {
terminateOnEvalImprovementNumOfEpoch = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useMemoryEvaluator")) {
useMemoryEvaluator = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("suppressTestDebug")) {
suppressTestDebug = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useOWLQN")) {
useOWLQN = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("printWeights")) {
printWeights = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("totalDataSlice")) {
totalDataSlice = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("numOfSlices")) {
numOfSlices = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("regularizeSoftmaxTieParam")) {
regularizeSoftmaxTieParam = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("softmaxTieLambda")) {
softmaxTieLambda = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("totalFeatureSlice")) {
totalFeatureSlice = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("numOfFeatureSlices")) {
numOfFeatureSlices = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("addBiasToEmbedding")) {
addBiasToEmbedding = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("hardcodeSoftmaxOutputWeights")) {
hardcodeSoftmaxOutputWeights = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("entityMatrix")) {
entityMatrix = val;
} else if (key.equalsIgnoreCase("multiThreadClassifier")) {
multiThreadClassifier = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useDualDecomp")) {
useDualDecomp = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("biAlignmentPriorIsPMI")) {
biAlignmentPriorIsPMI = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("dampDDStepSizeWithAlignmentProb")) {
dampDDStepSizeWithAlignmentProb = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("dualDecompAlignment")) {
dualDecompAlignment = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("dualDecompInitialStepSizeAlignment")) {
dualDecompInitialStepSizeAlignment = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("dualDecompNotBIO")) {
dualDecompNotBIO = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("berkeleyAlignerLoadPath")) {
berkeleyAlignerLoadPath = val;
} else if (key.equalsIgnoreCase("useBerkeleyAlignerForViterbi")) {
useBerkeleyAlignerForViterbi = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useBerkeleyCompetitivePosterior")) {
useBerkeleyCompetitivePosterior = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useDenero")) {
useDenero = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("alignDDAlpha")) {
alignDDAlpha = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("factorInBiEdgePotential")) {
factorInBiEdgePotential = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("noNeighborConstraints")) {
noNeighborConstraints = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("includeC2EViterbi")) {
includeC2EViterbi = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("initWithPosterior")) {
initWithPosterior = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("nerSlowerTimes")) {
nerSlowerTimes = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("nerSkipFirstK")) {
nerSkipFirstK = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("powerAlignProb")) {
powerAlignProb = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("powerAlignProbAsAddition")) {
powerAlignProbAsAddition = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("initWithNERPosterior")) {
initWithNERPosterior = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("applyNERPenalty")) {
applyNERPenalty = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useGenericFeatures")) {
useGenericFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("printFactorTable")) {
printFactorTable = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAdaGradFOBOS")) {
useAdaGradFOBOS = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("initRate")) {
initRate = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("groupByFeatureTemplate")) {
groupByFeatureTemplate = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("groupByOutputClass")) {
groupByOutputClass = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("priorAlpha")) {
priorAlpha = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("splitWordRegex")){
splitWordRegex = val;
} else if (key.equalsIgnoreCase("groupByInput")){
groupByInput = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("groupByHiddenUnit")){
groupByHiddenUnit = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("unigramLM")){
unigramLM = val;
} else if (key.equalsIgnoreCase("bigramLM")){
bigramLM = val;
} else if (key.equalsIgnoreCase("wordSegBeamSize")){
wordSegBeamSize = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("vocabFile")){
vocabFile = val;
} else if (key.equalsIgnoreCase("normalizedFile")){
normalizedFile = val;
} else if (key.equalsIgnoreCase("averagePerceptron")){
averagePerceptron = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("loadCRFSegmenterPath")){
loadCRFSegmenterPath = val;
} else if (key.equalsIgnoreCase("loadPCTSegmenterPath")){
loadPCTSegmenterPath = val;
} else if (key.equalsIgnoreCase("crfSegmenterProp")){
crfSegmenterProp = val;
} else if (key.equalsIgnoreCase("pctSegmenterProp")){
pctSegmenterProp = val;
} else if (key.equalsIgnoreCase("dualDecompMaxItr")){
dualDecompMaxItr = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("dualDecompInitialStepSize")){
dualDecompInitialStepSize = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("dualDecompDebug")){
dualDecompDebug = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("intermediateSegmenterOut")){
intermediateSegmenterOut = val;
} else if (key.equalsIgnoreCase("intermediateSegmenterModel")){
intermediateSegmenterModel = val;
} else if (key.equalsIgnoreCase("useCWSWordFeatures")){
useCWSWordFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useCWSWordFeaturesAll")){
useCWSWordFeaturesAll = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useCWSWordFeaturesBigram")){
useCWSWordFeaturesBigram = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("pctSegmenterLenAdjust")){
pctSegmenterLenAdjust = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useTrainLexicon")){
useTrainLexicon = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useCWSFeatures")){
useCWSFeatures = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("appendLC")){
appendLC = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("perceptronDebug")){
perceptronDebug = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("pctSegmenterScaleByCRF")){
pctSegmenterScaleByCRF = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("pctSegmenterScale")){
pctSegmenterScale = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("separateASCIIandRange")){
separateASCIIandRange = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("dropoutRate")){
dropoutRate = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("dropoutScale")){
dropoutScale = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("multiThreadGrad")){
multiThreadGrad = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("maxQNItr")){
maxQNItr = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("dropoutApprox")){
dropoutApprox = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("unsupDropoutFile")){
unsupDropoutFile = val;
} else if (key.equalsIgnoreCase("unsupDropoutScale")){
unsupDropoutScale = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("startEvaluateIters")){
startEvaluateIters = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("multiThreadPerceptron")){
multiThreadPerceptron = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("lazyUpdate")){
lazyUpdate = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("featureCountThresh")){
featureCountThresh = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("serializeWeightsTo")) {
serializeWeightsTo = val;
} else if (key.equalsIgnoreCase("geDebug")){
geDebug = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("doFeatureDiscovery")){
doFeatureDiscovery = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("loadWeightsFrom")) {
loadWeightsFrom = val;
} else if (key.equalsIgnoreCase("loadClassIndexFrom")) {
loadClassIndexFrom = val;
} else if (key.equalsIgnoreCase("serializeClassIndexTo")) {
serializeClassIndexTo = val;
} else if (key.equalsIgnoreCase("learnCHBasedOnEN")){
learnCHBasedOnEN = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("learnENBasedOnCH")){
learnENBasedOnCH = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("loadWeightsFromEN")){
loadWeightsFromEN = val;
} else if (key.equalsIgnoreCase("loadWeightsFromCH")){
loadWeightsFromCH = val;
} else if (key.equalsIgnoreCase("serializeToEN")){
serializeToEN = val;
} else if (key.equalsIgnoreCase("serializeToCH")){
serializeToCH = val;
} else if (key.equalsIgnoreCase("testFileEN")){
testFileEN = val;
} else if (key.equalsIgnoreCase("testFileCH")){
testFileCH = val;
} else if (key.equalsIgnoreCase("unsupFileEN")){
unsupFileEN = val;
} else if (key.equalsIgnoreCase("unsupFileCH")){
unsupFileCH = val;
} else if (key.equalsIgnoreCase("unsupAlignFile")){
unsupAlignFile = val;
} else if (key.equalsIgnoreCase("supFileEN")){
supFileEN = val;
} else if (key.equalsIgnoreCase("supFileCH")){
supFileCH = val;
} else if (key.equalsIgnoreCase("serializeFeatureIndexTo")){
serializeFeatureIndexTo = val;
} else if (key.equalsIgnoreCase("serializeFeatureIndexToText")){
serializeFeatureIndexToText = val;
} else if (key.equalsIgnoreCase("loadFeatureIndexFromEN")){
loadFeatureIndexFromEN = val;
} else if (key.equalsIgnoreCase("loadFeatureIndexFromCH")){
loadFeatureIndexFromCH = val;
} else if (key.equalsIgnoreCase("lambdaEN")){
lambdaEN = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("lambdaCH")){
lambdaCH = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("alternateTraining")){
alternateTraining = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("weightByEntropy")){
weightByEntropy = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useKL")){
useKL = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useHardGE")){
useHardGE = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useCRFforUnsup")){
useCRFforUnsup = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useGEforSup")){
useGEforSup = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useKnownLCWords")) {
log.info("useKnownLCWords is deprecated; see maxAdditionalKnownLCWords (true = -1, false = 0)");
maxAdditionalKnownLCWords = Boolean.parseBoolean(val) ? -1: 0;
} else if (key.equalsIgnoreCase("useNoisyLabel")) {
useNoisyLabel = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("errorMatrix")) {
errorMatrix = val;
} else if (key.equalsIgnoreCase("printTrainLabels")){
printTrainLabels = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("labelDictionaryCutoff")) {
labelDictionaryCutoff = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("useAdaDelta")){
useAdaDelta = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("useAdaDiff")){
useAdaDiff = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("adaGradEps")){
adaGradEps = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("adaDeltaRho")){
adaDeltaRho = Double.parseDouble(val);
} else if (key.equalsIgnoreCase("useRandomSeed")){
useRandomSeed = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("terminateOnAvgImprovement")){
terminateOnAvgImprovement = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("strictGoodCoNLL")) {
strictGoodCoNLL = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("removeStrictGoodCoNLLDuplicates")) {
removeStrictGoodCoNLLDuplicates = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("priorModelFactory")) {
priorModelFactory = val;
} else if (key.equalsIgnoreCase("maxAdditionalKnownLCWords")) {
maxAdditionalKnownLCWords = Integer.parseInt(val);
} else if (key.equalsIgnoreCase("showNCCInfo")) {
showNCCInfo = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("showCCInfo")) {
showCCInfo = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("crfToExamine")) {
crfToExamine = val;
} else if (key.equalsIgnoreCase("ner.useSUTime")) {
useSUTime = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("ner.applyNumericClassifiers")) {
applyNumericClassifiers = Boolean.parseBoolean(val);
} else if (key.equalsIgnoreCase("ner.combinationMode")) {
combinationMode = val;
} else if (key.equalsIgnoreCase("ner.model")) {
nerModel = val;
} else if (key.equalsIgnoreCase("sutime.language")) {
} else if (key.equalsIgnoreCase("dict2name")) {
dict2name = val;
// ADD VALUE ABOVE HERE
} else if ( ! key.isEmpty() && ! key.equals("prop")) {
log.info("Unknown property: |" + key + '|');
}
}
if (startFold > numFolds) {
log.info("startFold > numFolds -> setting startFold to 1");
startFold = 1;
}
if (endFold > numFolds) {
log.info("endFold > numFolds -> setting to numFolds");
endFold = numFolds;
}
if (combo) {
splitDocuments = false;
}
stringRep = sb.toString();
} // end setProperties()
public static Map<String, Integer> flagsToNumArgs() {
Map<String, Integer> numArgs = new HashMap<String, Integer>();
numArgs.put("maxDocSize", 1);
return numArgs;
}
// Thang Sep13: refactor to be used for multiple factories.
private static String getFeatureFactory(String val){
if (val.equalsIgnoreCase("SuperSimpleFeatureFactory")) {
val = "edu.stanford.nlp.sequences.SuperSimpleFeatureFactory";
} else if (val.equalsIgnoreCase("NERFeatureFactory")) {
val = "edu.stanford.nlp.ie.NERFeatureFactory";
} else if (val.equalsIgnoreCase("GazNERFeatureFactory")) {
val = "edu.stanford.nlp.sequences.GazNERFeatureFactory";
} else if (val.equalsIgnoreCase("IncludeAllFeatureFactory")) {
val = "edu.stanford.nlp.sequences.IncludeAllFeatureFactory";
} else if (val.equalsIgnoreCase("PhraseFeatureFactory")) {
val = "edu.stanford.nlp.article.extraction.PhraseFeatureFactory";
} else if (val.equalsIgnoreCase("EmbeddingFeatureFactory")) {
val = "edu.stanford.nlp.ie.EmbeddingFeatureFactory";
}
return val;
}
/**
* Print the properties specified by this object.
*
* @return A String describing the properties specified by this object.
*/
@Override
public String toString() {
return stringRep;
}
/**
* note that this does *not* return string representation of arrays, lists and
* enums
*
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public String getNotNullTrueStringRep() {
try {
StringBuilder rep = new StringBuilder();
String joiner = "\n";
Field[] f = this.getClass().getFields();
for (Field ff : f) {
String name = ff.getName();
Class<?> type = ff.getType();
if (type.equals(Boolean.class) || type.equals(boolean.class)) {
boolean val = ff.getBoolean(this);
if (val) {
rep.append(joiner).append(name).append('=').append(val);
}
} else if (type.equals(String.class)) {
String val = (String) ff.get(this);
if (val != null)
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(Double.class)) {
Double val = (Double) ff.get(this);
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(double.class)) {
double val = ff.getDouble(this);
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(Integer.class)) {
Integer val = (Integer) ff.get(this);
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(int.class)) {
int val = ff.getInt(this);
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(Float.class)) {
Float val = (Float) ff.get(this);
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(float.class)) {
float val = ff.getFloat(this);
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(Byte.class)) {
Byte val = (Byte) ff.get(this);
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(byte.class)) {
byte val = ff.getByte(this);
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(char.class)) {
char val = ff.getChar(this);
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(Long.class)) {
Long val = (Long) ff.get(this);
rep.append(joiner).append(name).append('=').append(val);
} else if (type.equals(long.class)) {
long val = ff.getLong(this);
rep.append(joiner).append(name).append('=').append(val);
}
}
return rep.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
} // end class SeqClassifierFlags
| stanfordnlp/CoreNLP | src/edu/stanford/nlp/sequences/SeqClassifierFlags.java |
45,350 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.common;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* An immutable representation of a subset of the nodes, topics, and partitions in the Kafka cluster.
*/
public final class Cluster {
private final boolean isBootstrapConfigured;
private final List<Node> nodes;
private final Set<String> unauthorizedTopics;
private final Set<String> invalidTopics;
private final Set<String> internalTopics;
private final Node controller;
private final Map<TopicPartition, PartitionInfo> partitionsByTopicPartition;
private final Map<String, List<PartitionInfo>> partitionsByTopic;
private final Map<String, List<PartitionInfo>> availablePartitionsByTopic;
private final Map<Integer, List<PartitionInfo>> partitionsByNode;
private final Map<Integer, Node> nodesById;
private final ClusterResource clusterResource;
private final Map<String, Uuid> topicIds;
private final Map<Uuid, String> topicNames;
/**
* Create a new cluster with the given id, nodes and partitions
* @param nodes The nodes in the cluster
* @param partitions Information about a subset of the topic-partitions this cluster hosts
*/
public Cluster(String clusterId,
Collection<Node> nodes,
Collection<PartitionInfo> partitions,
Set<String> unauthorizedTopics,
Set<String> internalTopics) {
this(clusterId, false, nodes, partitions, unauthorizedTopics, Collections.emptySet(), internalTopics, null, Collections.emptyMap());
}
/**
* Create a new cluster with the given id, nodes and partitions
* @param nodes The nodes in the cluster
* @param partitions Information about a subset of the topic-partitions this cluster hosts
*/
public Cluster(String clusterId,
Collection<Node> nodes,
Collection<PartitionInfo> partitions,
Set<String> unauthorizedTopics,
Set<String> internalTopics,
Node controller) {
this(clusterId, false, nodes, partitions, unauthorizedTopics, Collections.emptySet(), internalTopics, controller, Collections.emptyMap());
}
/**
* Create a new cluster with the given id, nodes and partitions
* @param nodes The nodes in the cluster
* @param partitions Information about a subset of the topic-partitions this cluster hosts
*/
public Cluster(String clusterId,
Collection<Node> nodes,
Collection<PartitionInfo> partitions,
Set<String> unauthorizedTopics,
Set<String> invalidTopics,
Set<String> internalTopics,
Node controller) {
this(clusterId, false, nodes, partitions, unauthorizedTopics, invalidTopics, internalTopics, controller, Collections.emptyMap());
}
/**
* Create a new cluster with the given id, nodes, partitions and topicIds
* @param nodes The nodes in the cluster
* @param partitions Information about a subset of the topic-partitions this cluster hosts
*/
public Cluster(String clusterId,
Collection<Node> nodes,
Collection<PartitionInfo> partitions,
Set<String> unauthorizedTopics,
Set<String> invalidTopics,
Set<String> internalTopics,
Node controller,
Map<String, Uuid> topicIds) {
this(clusterId, false, nodes, partitions, unauthorizedTopics, invalidTopics, internalTopics, controller, topicIds);
}
private Cluster(String clusterId,
boolean isBootstrapConfigured,
Collection<Node> nodes,
Collection<PartitionInfo> partitions,
Set<String> unauthorizedTopics,
Set<String> invalidTopics,
Set<String> internalTopics,
Node controller,
Map<String, Uuid> topicIds) {
this.isBootstrapConfigured = isBootstrapConfigured;
this.clusterResource = new ClusterResource(clusterId);
// make a randomized, unmodifiable copy of the nodes
List<Node> copy = new ArrayList<>(nodes);
Collections.shuffle(copy);
this.nodes = Collections.unmodifiableList(copy);
// Index the nodes for quick lookup
Map<Integer, Node> tmpNodesById = new HashMap<>();
Map<Integer, List<PartitionInfo>> tmpPartitionsByNode = new HashMap<>(nodes.size());
for (Node node : nodes) {
tmpNodesById.put(node.id(), node);
// Populate the map here to make it easy to add the partitions per node efficiently when iterating over
// the partitions
tmpPartitionsByNode.put(node.id(), new ArrayList<>());
}
this.nodesById = Collections.unmodifiableMap(tmpNodesById);
// index the partition infos by topic, topic+partition, and node
// note that this code is performance sensitive if there are a large number of partitions so we are careful
// to avoid unnecessary work
Map<TopicPartition, PartitionInfo> tmpPartitionsByTopicPartition = new HashMap<>(partitions.size());
Map<String, List<PartitionInfo>> tmpPartitionsByTopic = new HashMap<>();
for (PartitionInfo p : partitions) {
tmpPartitionsByTopicPartition.put(new TopicPartition(p.topic(), p.partition()), p);
tmpPartitionsByTopic.computeIfAbsent(p.topic(), topic -> new ArrayList<>()).add(p);
// The leader may not be known
if (p.leader() == null || p.leader().isEmpty())
continue;
// If it is known, its node information should be available
List<PartitionInfo> partitionsForNode = Objects.requireNonNull(tmpPartitionsByNode.get(p.leader().id()));
partitionsForNode.add(p);
}
// Update the values of `tmpPartitionsByNode` to contain unmodifiable lists
for (Map.Entry<Integer, List<PartitionInfo>> entry : tmpPartitionsByNode.entrySet()) {
tmpPartitionsByNode.put(entry.getKey(), Collections.unmodifiableList(entry.getValue()));
}
// Populate `tmpAvailablePartitionsByTopic` and update the values of `tmpPartitionsByTopic` to contain
// unmodifiable lists
Map<String, List<PartitionInfo>> tmpAvailablePartitionsByTopic = new HashMap<>(tmpPartitionsByTopic.size());
for (Map.Entry<String, List<PartitionInfo>> entry : tmpPartitionsByTopic.entrySet()) {
String topic = entry.getKey();
List<PartitionInfo> partitionsForTopic = Collections.unmodifiableList(entry.getValue());
tmpPartitionsByTopic.put(topic, partitionsForTopic);
// Optimise for the common case where all partitions are available
boolean foundUnavailablePartition = partitionsForTopic.stream().anyMatch(p -> p.leader() == null);
List<PartitionInfo> availablePartitionsForTopic;
if (foundUnavailablePartition) {
availablePartitionsForTopic = new ArrayList<>(partitionsForTopic.size());
for (PartitionInfo p : partitionsForTopic) {
if (p.leader() != null)
availablePartitionsForTopic.add(p);
}
availablePartitionsForTopic = Collections.unmodifiableList(availablePartitionsForTopic);
} else {
availablePartitionsForTopic = partitionsForTopic;
}
tmpAvailablePartitionsByTopic.put(topic, availablePartitionsForTopic);
}
this.partitionsByTopicPartition = Collections.unmodifiableMap(tmpPartitionsByTopicPartition);
this.partitionsByTopic = Collections.unmodifiableMap(tmpPartitionsByTopic);
this.availablePartitionsByTopic = Collections.unmodifiableMap(tmpAvailablePartitionsByTopic);
this.partitionsByNode = Collections.unmodifiableMap(tmpPartitionsByNode);
this.topicIds = Collections.unmodifiableMap(topicIds);
Map<Uuid, String> tmpTopicNames = new HashMap<>();
topicIds.forEach((key, value) -> tmpTopicNames.put(value, key));
this.topicNames = Collections.unmodifiableMap(tmpTopicNames);
this.unauthorizedTopics = Collections.unmodifiableSet(unauthorizedTopics);
this.invalidTopics = Collections.unmodifiableSet(invalidTopics);
this.internalTopics = Collections.unmodifiableSet(internalTopics);
this.controller = controller;
}
/**
* Create an empty cluster instance with no nodes and no topic-partitions.
*/
public static Cluster empty() {
return new Cluster(null, new ArrayList<>(0), new ArrayList<>(0), Collections.emptySet(),
Collections.emptySet(), null);
}
/**
* Create a "bootstrap" cluster using the given list of host/ports
* @param addresses The addresses
* @return A cluster for these hosts/ports
*/
public static Cluster bootstrap(List<InetSocketAddress> addresses) {
List<Node> nodes = new ArrayList<>();
int nodeId = -1;
for (InetSocketAddress address : addresses)
nodes.add(new Node(nodeId--, address.getHostString(), address.getPort()));
return new Cluster(null, true, nodes, new ArrayList<>(0),
Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), null, Collections.emptyMap());
}
/**
* Return a copy of this cluster combined with `partitions`.
*/
public Cluster withPartitions(Map<TopicPartition, PartitionInfo> partitions) {
Map<TopicPartition, PartitionInfo> combinedPartitions = new HashMap<>(this.partitionsByTopicPartition);
combinedPartitions.putAll(partitions);
return new Cluster(clusterResource.clusterId(), this.nodes, combinedPartitions.values(),
new HashSet<>(this.unauthorizedTopics), new HashSet<>(this.invalidTopics),
new HashSet<>(this.internalTopics), this.controller);
}
/**
* @return The known set of nodes
*/
public List<Node> nodes() {
return this.nodes;
}
/**
* Get the node by the node id (or null if the node is not online or does not exist)
* @param id The id of the node
* @return The node, or null if the node is not online or does not exist
*/
public Node nodeById(int id) {
return this.nodesById.get(id);
}
/**
* Get the node by node id if the replica for the given partition is online
* @param partition
* @param id
* @return the node
*/
public Optional<Node> nodeIfOnline(TopicPartition partition, int id) {
Node node = nodeById(id);
PartitionInfo partitionInfo = partition(partition);
if (node != null && partitionInfo != null &&
!Arrays.asList(partitionInfo.offlineReplicas()).contains(node) &&
Arrays.asList(partitionInfo.replicas()).contains(node)) {
return Optional.of(node);
} else {
return Optional.empty();
}
}
/**
* Get the current leader for the given topic-partition
* @param topicPartition The topic and partition we want to know the leader for
* @return The node that is the leader for this topic-partition, or null if there is currently no leader
*/
public Node leaderFor(TopicPartition topicPartition) {
PartitionInfo info = partitionsByTopicPartition.get(topicPartition);
if (info == null)
return null;
else
return info.leader();
}
/**
* Get the metadata for the specified partition
* @param topicPartition The topic and partition to fetch info for
* @return The metadata about the given topic and partition, or null if none is found
*/
public PartitionInfo partition(TopicPartition topicPartition) {
return partitionsByTopicPartition.get(topicPartition);
}
/**
* Get the list of partitions for this topic
* @param topic The topic name
* @return A list of partitions
*/
public List<PartitionInfo> partitionsForTopic(String topic) {
return partitionsByTopic.getOrDefault(topic, Collections.emptyList());
}
/**
* Get the number of partitions for the given topic.
* @param topic The topic to get the number of partitions for
* @return The number of partitions or null if there is no corresponding metadata
*/
public Integer partitionCountForTopic(String topic) {
List<PartitionInfo> partitions = this.partitionsByTopic.get(topic);
return partitions == null ? null : partitions.size();
}
/**
* Get the list of available partitions for this topic
* @param topic The topic name
* @return A list of partitions
*/
public List<PartitionInfo> availablePartitionsForTopic(String topic) {
return availablePartitionsByTopic.getOrDefault(topic, Collections.emptyList());
}
/**
* Get the list of partitions whose leader is this node
* @param nodeId The node id
* @return A list of partitions
*/
public List<PartitionInfo> partitionsForNode(int nodeId) {
return partitionsByNode.getOrDefault(nodeId, Collections.emptyList());
}
/**
* Get all topics.
* @return a set of all topics
*/
public Set<String> topics() {
return partitionsByTopic.keySet();
}
public Set<String> unauthorizedTopics() {
return unauthorizedTopics;
}
public Set<String> invalidTopics() {
return invalidTopics;
}
public Set<String> internalTopics() {
return internalTopics;
}
public boolean isBootstrapConfigured() {
return isBootstrapConfigured;
}
public ClusterResource clusterResource() {
return clusterResource;
}
public Node controller() {
return controller;
}
public Collection<Uuid> topicIds() {
return topicIds.values();
}
public Uuid topicId(String topic) {
return topicIds.getOrDefault(topic, Uuid.ZERO_UUID);
}
public String topicName(Uuid topicId) {
return topicNames.get(topicId);
}
@Override
public String toString() {
return "Cluster(id = " + clusterResource.clusterId() + ", nodes = " + this.nodes +
", partitions = " + this.partitionsByTopicPartition.values() + ", controller = " + controller + ")";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cluster cluster = (Cluster) o;
return isBootstrapConfigured == cluster.isBootstrapConfigured &&
Objects.equals(nodes, cluster.nodes) &&
Objects.equals(unauthorizedTopics, cluster.unauthorizedTopics) &&
Objects.equals(invalidTopics, cluster.invalidTopics) &&
Objects.equals(internalTopics, cluster.internalTopics) &&
Objects.equals(controller, cluster.controller) &&
Objects.equals(partitionsByTopicPartition, cluster.partitionsByTopicPartition) &&
Objects.equals(clusterResource, cluster.clusterResource);
}
@Override
public int hashCode() {
return Objects.hash(isBootstrapConfigured, nodes, unauthorizedTopics, invalidTopics, internalTopics, controller,
partitionsByTopicPartition, clusterResource);
}
}
| apache/kafka | clients/src/main/java/org/apache/kafka/common/Cluster.java |
45,351 | /*
* This is the source code of Telegram for Android v. 5.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.ui.Components;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.CharacterStyle;
import android.util.Log;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.inputmethod.EditorInfo;
import android.widget.FrameLayout;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.CodeHighlighting;
import org.telegram.messenger.Emoji;
import org.telegram.messenger.FileLog;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.MediaDataController;
import org.telegram.messenger.R;
import org.telegram.messenger.utils.CopyUtilities;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.AlertDialogDecor;
import org.telegram.ui.ActionBar.Theme;
import java.util.List;
public class EditTextCaption extends EditTextBoldCursor {
private static final int ACCESSIBILITY_ACTION_SHARE = 0x10000000;
private String caption;
private StaticLayout captionLayout;
private int userNameLength;
private int xOffset;
private int yOffset;
private int triesCount = 0;
private boolean copyPasteShowed;
private int hintColor;
private EditTextCaptionDelegate delegate;
private int selectionStart = -1;
private int selectionEnd = -1;
private boolean allowTextEntitiesIntersection;
private int lineCount;
private boolean isInitLineCount;
private final Theme.ResourcesProvider resourcesProvider;
private AlertDialog creationLinkDialog;
public boolean adaptiveCreateLinkDialog;
public interface EditTextCaptionDelegate {
void onSpansChanged();
}
public EditTextCaption(Context context, Theme.ResourcesProvider resourcesProvider) {
super(context);
this.resourcesProvider = resourcesProvider;
quoteColor = Theme.getColor(Theme.key_chat_inQuote, resourcesProvider);
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (lineCount != getLineCount()) {
if (!isInitLineCount && getMeasuredWidth() > 0) {
onLineCountChanged(lineCount, getLineCount());
}
lineCount = getLineCount();
}
}
});
setClipToPadding(true);
}
protected void onLineCountChanged(int oldLineCount, int newLineCount) {
}
public void setCaption(String value) {
if ((caption == null || caption.length() == 0) && (value == null || value.length() == 0) || caption != null && caption.equals(value)) {
return;
}
caption = value;
if (caption != null) {
caption = caption.replace('\n', ' ');
}
requestLayout();
}
public void setDelegate(EditTextCaptionDelegate editTextCaptionDelegate) {
delegate = editTextCaptionDelegate;
}
public void setAllowTextEntitiesIntersection(boolean value) {
allowTextEntitiesIntersection = value;
}
public void makeSelectedBold() {
TextStyleSpan.TextStyleRun run = new TextStyleSpan.TextStyleRun();
run.flags |= TextStyleSpan.FLAG_STYLE_BOLD;
applyTextStyleToSelection(new TextStyleSpan(run));
}
public void makeSelectedSpoiler() {
TextStyleSpan.TextStyleRun run = new TextStyleSpan.TextStyleRun();
run.flags |= TextStyleSpan.FLAG_STYLE_SPOILER;
applyTextStyleToSelection(new TextStyleSpan(run));
invalidateSpoilers();
}
public void makeSelectedItalic() {
TextStyleSpan.TextStyleRun run = new TextStyleSpan.TextStyleRun();
run.flags |= TextStyleSpan.FLAG_STYLE_ITALIC;
applyTextStyleToSelection(new TextStyleSpan(run));
}
public void makeSelectedMono() {
TextStyleSpan.TextStyleRun run = new TextStyleSpan.TextStyleRun();
run.flags |= TextStyleSpan.FLAG_STYLE_MONO;
applyTextStyleToSelection(new TextStyleSpan(run));
}
public void makeSelectedStrike() {
TextStyleSpan.TextStyleRun run = new TextStyleSpan.TextStyleRun();
run.flags |= TextStyleSpan.FLAG_STYLE_STRIKE;
applyTextStyleToSelection(new TextStyleSpan(run));
}
public void makeSelectedUnderline() {
TextStyleSpan.TextStyleRun run = new TextStyleSpan.TextStyleRun();
run.flags |= TextStyleSpan.FLAG_STYLE_UNDERLINE;
applyTextStyleToSelection(new TextStyleSpan(run));
}
public void makeSelectedQuote() {
int start, end;
if (selectionStart >= 0 && selectionEnd >= 0) {
start = selectionStart;
end = selectionEnd;
selectionStart = selectionEnd = -1;
} else {
start = getSelectionStart();
end = getSelectionEnd();
}
final int setSelection = QuoteSpan.putQuoteToEditable(getText(), start, end);
if (setSelection >= 0) {
setSelection(setSelection);
resetFontMetricsCache();
}
invalidateQuotes(true);
invalidateSpoilers();
}
public void makeSelectedUrl() {
AlertDialog.Builder builder;
if (adaptiveCreateLinkDialog) {
builder = new AlertDialogDecor.Builder(getContext(), resourcesProvider);
} else {
builder = new AlertDialog.Builder(getContext(), resourcesProvider);
}
builder.setTitle(LocaleController.getString("CreateLink", R.string.CreateLink));
final EditTextBoldCursor editText = new EditTextBoldCursor(getContext()) {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(64), MeasureSpec.EXACTLY));
}
};
editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
editText.setText("http://");
editText.setTextColor(getThemedColor(Theme.key_dialogTextBlack));
editText.setHintText(LocaleController.getString("URL", R.string.URL));
editText.setHeaderHintColor(getThemedColor(Theme.key_windowBackgroundWhiteBlueHeader));
editText.setSingleLine(true);
editText.setFocusable(true);
editText.setTransformHintToHeader(true);
editText.setLineColors(getThemedColor(Theme.key_windowBackgroundWhiteInputField), getThemedColor(Theme.key_windowBackgroundWhiteInputFieldActivated), getThemedColor(Theme.key_text_RedRegular));
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
editText.setBackgroundDrawable(null);
editText.requestFocus();
editText.setPadding(0, 0, 0, 0);
builder.setView(editText);
final int start;
final int end;
if (selectionStart >= 0 && selectionEnd >= 0) {
start = selectionStart;
end = selectionEnd;
selectionStart = selectionEnd = -1;
} else {
start = getSelectionStart();
end = getSelectionEnd();
}
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (dialogInterface, i) -> {
Editable editable = getText();
CharacterStyle[] spans = editable.getSpans(start, end, CharacterStyle.class);
if (spans != null && spans.length > 0) {
for (int a = 0; a < spans.length; a++) {
CharacterStyle oldSpan = spans[a];
if (!(oldSpan instanceof AnimatedEmojiSpan) && !(oldSpan instanceof QuoteSpan.QuoteStyleSpan)) {
int spanStart = editable.getSpanStart(oldSpan);
int spanEnd = editable.getSpanEnd(oldSpan);
editable.removeSpan(oldSpan);
if (spanStart < start) {
editable.setSpan(oldSpan, spanStart, start, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (spanEnd > end) {
editable.setSpan(oldSpan, end, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
}
try {
editable.setSpan(new URLSpanReplacement(editText.getText().toString()), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception ignore) {
}
if (delegate != null) {
delegate.onSpansChanged();
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
if (adaptiveCreateLinkDialog) {
creationLinkDialog = builder.create();
creationLinkDialog.setOnDismissListener(dialog -> {
creationLinkDialog = null;
requestFocus();
});
creationLinkDialog.setOnShowListener(dialog -> {
editText.requestFocus();
AndroidUtilities.showKeyboard(editText);
});
creationLinkDialog.showDelayed(250);
} else {
builder.show().setOnShowListener(dialog -> {
editText.requestFocus();
AndroidUtilities.showKeyboard(editText);
});
}
if (editText != null) {
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) editText.getLayoutParams();
if (layoutParams != null) {
if (layoutParams instanceof FrameLayout.LayoutParams) {
((FrameLayout.LayoutParams) layoutParams).gravity = Gravity.CENTER_HORIZONTAL;
}
layoutParams.rightMargin = layoutParams.leftMargin = AndroidUtilities.dp(24);
layoutParams.height = AndroidUtilities.dp(36);
editText.setLayoutParams(layoutParams);
}
editText.setSelection(0, editText.getText().length());
}
}
public boolean closeCreationLinkDialog() {
if (creationLinkDialog != null && creationLinkDialog.isShowing()) {
creationLinkDialog.dismiss();
return true;
}
return false;
}
public void makeSelectedRegular() {
applyTextStyleToSelection(null);
}
public void setSelectionOverride(int start, int end) {
selectionStart = start;
selectionEnd = end;
}
private void applyTextStyleToSelection(TextStyleSpan span) {
int start;
int end;
if (selectionStart >= 0 && selectionEnd >= 0) {
start = selectionStart;
end = selectionEnd;
selectionStart = selectionEnd = -1;
} else {
start = getSelectionStart();
end = getSelectionEnd();
}
MediaDataController.addStyleToText(span, start, end, getText(), allowTextEntitiesIntersection);
if (span == null) {
Editable editable = getText();
CodeHighlighting.Span[] code = editable.getSpans(start, end, CodeHighlighting.Span.class);
for (int i = 0; i < code.length; ++i)
editable.removeSpan(code[i]);
QuoteSpan[] quotes = editable.getSpans(start, end, QuoteSpan.class);
for (int i = 0; i < quotes.length; ++i) {
editable.removeSpan(quotes[i]);
editable.removeSpan(quotes[i].styleSpan);
}
if (quotes.length > 0) {
invalidateQuotes(true);
}
}
if (delegate != null) {
delegate.onSpansChanged();
}
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
if (Build.VERSION.SDK_INT < 23 && !hasWindowFocus && copyPasteShowed) {
return;
}
try {
super.onWindowFocusChanged(hasWindowFocus);
} catch (Throwable e) {
FileLog.e(e);
}
}
protected void onContextMenuOpen() {
}
protected void onContextMenuClose() {
}
private ActionMode.Callback overrideCallback(final ActionMode.Callback callback) {
ActionMode.Callback wrap = new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
copyPasteShowed = true;
onContextMenuOpen();
return callback.onCreateActionMode(mode, menu);
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return callback.onPrepareActionMode(mode, menu);
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (performMenuAction(item.getItemId())) {
mode.finish();
return true;
}
try {
return callback.onActionItemClicked(mode, item);
} catch (Exception ignore) {
}
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
copyPasteShowed = false;
onContextMenuClose();
callback.onDestroyActionMode(mode);
}
};
if (Build.VERSION.SDK_INT >= 23) {
return new ActionMode.Callback2() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return wrap.onCreateActionMode(mode, menu);
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return wrap.onPrepareActionMode(mode, menu);
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return wrap.onActionItemClicked(mode, item);
}
@Override
public void onDestroyActionMode(ActionMode mode) {
wrap.onDestroyActionMode(mode);
}
@Override
public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
if (callback instanceof ActionMode.Callback2) {
((ActionMode.Callback2) callback).onGetContentRect(mode, view, outRect);
} else {
super.onGetContentRect(mode, view, outRect);
}
}
};
} else {
return wrap;
}
}
public boolean performMenuAction(int itemId) {
if (itemId == R.id.menu_regular) {
makeSelectedRegular();
return true;
} else if (itemId == R.id.menu_bold) {
makeSelectedBold();
return true;
} else if (itemId == R.id.menu_italic) {
makeSelectedItalic();
return true;
} else if (itemId == R.id.menu_mono) {
makeSelectedMono();
return true;
} else if (itemId == R.id.menu_link) {
makeSelectedUrl();
return true;
} else if (itemId == R.id.menu_strike) {
makeSelectedStrike();
return true;
} else if (itemId == R.id.menu_underline) {
makeSelectedUnderline();
return true;
} else if (itemId == R.id.menu_spoiler) {
makeSelectedSpoiler();
return true;
} else if (itemId == R.id.menu_quote) {
makeSelectedQuote();
return true;
}
return false;
}
@Override
public ActionMode startActionMode(final ActionMode.Callback callback, int type) {
return super.startActionMode(overrideCallback(callback), type);
}
@Override
public ActionMode startActionMode(final ActionMode.Callback callback) {
return super.startActionMode(overrideCallback(callback));
}
@SuppressLint("DrawAllocation")
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
isInitLineCount = getMeasuredWidth() == 0 && getMeasuredHeight() == 0;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (isInitLineCount) {
lineCount = getLineCount();
}
isInitLineCount = false;
} catch (Exception e) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), AndroidUtilities.dp(51));
FileLog.e(e);
}
captionLayout = null;
if (caption != null && caption.length() > 0) {
CharSequence text = getText();
if (text.length() > 1 && text.charAt(0) == '@') {
int index = TextUtils.indexOf(text, ' ');
if (index != -1) {
TextPaint paint = getPaint();
CharSequence str = text.subSequence(0, index + 1);
int size = (int) Math.ceil(paint.measureText(text, 0, index + 1));
int width = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
userNameLength = str.length();
CharSequence captionFinal = TextUtils.ellipsize(caption, paint, width - size, TextUtils.TruncateAt.END);
xOffset = size;
try {
captionLayout = new StaticLayout(captionFinal, getPaint(), width - size, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
if (captionLayout.getLineCount() > 0) {
xOffset += -captionLayout.getLineLeft(0);
}
yOffset = (getMeasuredHeight() - captionLayout.getLineBottom(0)) / 2 + AndroidUtilities.dp(0.5f);
} catch (Exception e) {
FileLog.e(e);
}
}
}
}
}
public String getCaption() {
return caption;
}
@Override
public void setHintColor(int value) {
super.setHintColor(value);
hintColor = value;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.translate(0, offsetY);
super.onDraw(canvas);
try {
if (captionLayout != null && userNameLength == length()) {
Paint paint = getPaint();
int oldColor = getPaint().getColor();
paint.setColor(hintColor);
canvas.save();
canvas.translate(xOffset, yOffset);
captionLayout.draw(canvas);
canvas.restore();
paint.setColor(oldColor);
}
} catch (Exception e) {
FileLog.e(e);
}
canvas.restore();
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
final AccessibilityNodeInfoCompat infoCompat = AccessibilityNodeInfoCompat.wrap(info);
if (!TextUtils.isEmpty(caption)) {
infoCompat.setHintText(caption);
}
final List<AccessibilityNodeInfoCompat.AccessibilityActionCompat> actions = infoCompat.getActionList();
for (int i = 0, size = actions.size(); i < size; i++) {
final AccessibilityNodeInfoCompat.AccessibilityActionCompat action = actions.get(i);
if (action.getId() == ACCESSIBILITY_ACTION_SHARE) {
infoCompat.removeAction(action);
break;
}
}
if (hasSelection()) {
infoCompat.addAction(new AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.menu_spoiler, LocaleController.getString("Spoiler", R.string.Spoiler)));
infoCompat.addAction(new AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.menu_bold, LocaleController.getString("Bold", R.string.Bold)));
infoCompat.addAction(new AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.menu_italic, LocaleController.getString("Italic", R.string.Italic)));
infoCompat.addAction(new AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.menu_mono, LocaleController.getString("Mono", R.string.Mono)));
infoCompat.addAction(new AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.menu_strike, LocaleController.getString("Strike", R.string.Strike)));
infoCompat.addAction(new AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.menu_underline, LocaleController.getString("Underline", R.string.Underline)));
infoCompat.addAction(new AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.menu_link, LocaleController.getString("CreateLink", R.string.CreateLink)));
infoCompat.addAction(new AccessibilityNodeInfoCompat.AccessibilityActionCompat(R.id.menu_regular, LocaleController.getString("Regular", R.string.Regular)));
}
}
@Override
public boolean performAccessibilityAction(int action, Bundle arguments) {
return performMenuAction(action) || super.performAccessibilityAction(action, arguments);
}
private int getThemedColor(int key) {
return Theme.getColor(key, resourcesProvider);
}
@Override
public boolean onTextContextMenuItem(int id) {
if (id == android.R.id.paste) {
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = clipboard.getPrimaryClip();
if (clipData != null && clipData.getItemCount() == 1 && clipData.getDescription().hasMimeType("text/html")) {
try {
String html = clipData.getItemAt(0).getHtmlText();
Spannable pasted = CopyUtilities.fromHTML(html);
Emoji.replaceEmoji(pasted, getPaint().getFontMetricsInt(), false, null);
AnimatedEmojiSpan[] spans = pasted.getSpans(0, pasted.length(), AnimatedEmojiSpan.class);
if (spans != null) {
for (int k = 0; k < spans.length; ++k) {
spans[k].applyFontMetrics(getPaint().getFontMetricsInt(), AnimatedEmojiDrawable.getCacheTypeForEnterView());
}
}
int start = Math.max(0, getSelectionStart());
int end = Math.min(getText().length(), getSelectionEnd());
QuoteSpan.QuoteStyleSpan[] quotesInSelection = getText().getSpans(start, end, QuoteSpan.QuoteStyleSpan.class);
if (quotesInSelection != null && quotesInSelection.length > 0) {
QuoteSpan.QuoteStyleSpan[] quotesToDelete = pasted.getSpans(0, pasted.length(), QuoteSpan.QuoteStyleSpan.class);
for (int i = 0; i < quotesToDelete.length; ++i) {
pasted.removeSpan(quotesToDelete[i]);
pasted.removeSpan(quotesToDelete[i].span);
}
} else {
QuoteSpan.normalizeQuotes(pasted);
}
setText(getText().replace(start, end, pasted));
setSelection(start + pasted.length(), start + pasted.length());
return true;
} catch (Exception e) {
FileLog.e(e);
}
}
} else if (id == android.R.id.copy) {
int start = Math.max(0, getSelectionStart());
int end = Math.min(getText().length(), getSelectionEnd());
try {
AndroidUtilities.addToClipboard(getText().subSequence(start, end));
return true;
} catch (Exception e) {
}
} else if (id == android.R.id.cut) {
int start = Math.max(0, getSelectionStart());
int end = Math.min(getText().length(), getSelectionEnd());
try {
AndroidUtilities.addToClipboard(getText().subSequence(start, end));
SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
if (start != 0) {
stringBuilder.append(getText().subSequence(0, start));
}
if (end != getText().length()) {
stringBuilder.append(getText().subSequence(end, getText().length()));
}
setText(stringBuilder);
setSelection(start, start);
return true;
} catch (Exception e) {
}
}
return super.onTextContextMenuItem(id);
}
}
| Telegram-FOSS-Team/Telegram-FOSS | TMessagesProj/src/main/java/org/telegram/ui/Components/EditTextCaption.java |
45,352 | // Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.actions;
import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAware;
import com.intellij.platform.ide.customization.ExternalProductResourceUrls;
import com.intellij.util.Url;
import org.jetbrains.annotations.NotNull;
public final class OnlineDocAction extends HelpActionBase implements DumbAware {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Url url = ExternalProductResourceUrls.getInstance().getGettingStartedPageUrl();
if (url != null) {
BrowserUtil.browse(url.toExternalForm());
}
}
@Override
public boolean isAvailable() {
return ExternalProductResourceUrls.getInstance().getGettingStartedPageUrl() != null;
}
@Override
public @NotNull ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.BGT;
}
}
| mikeckennedy/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/OnlineDocAction.java |
45,353 | package hex.tree;
import hex.Model;
import hex.genmodel.algos.tree.SharedTreeGraph;
import hex.genmodel.algos.tree.SharedTreeNode;
import hex.genmodel.algos.tree.SharedTreeSubgraph;
import hex.genmodel.algos.tree.SharedTreeGraphConverter;
import hex.schemas.TreeV3;
import water.Keyed;
import water.MemoryManager;
import water.api.Handler;
import java.util.*;
import java.util.stream.IntStream;
import static hex.tree.TreeUtils.getResponseLevelIndex;
/**
* Handling requests for various model trees
*/
public class TreeHandler extends Handler {
private static final int NO_CHILD = -1;
public enum PlainLanguageRules {AUTO, TRUE, FALSE}
public TreeV3 getTree(final int version, final TreeV3 args) {
if (args.tree_number < 0) {
throw new IllegalArgumentException("Invalid tree number: " + args.tree_number + ". Tree number must be >= 0.");
}
final Keyed possibleModel = args.model.key().get();
if (possibleModel == null) throw new IllegalArgumentException("Given model does not exist: " + args.model.key().toString());
else if (!(possibleModel instanceof SharedTreeModel) && !(possibleModel instanceof SharedTreeGraphConverter)) {
throw new IllegalArgumentException("Given model is not tree-based.");
}
final SharedTreeSubgraph sharedTreeSubgraph;
if (possibleModel instanceof SharedTreeGraphConverter) {
final SharedTreeGraphConverter treeBackedModel = (SharedTreeGraphConverter) possibleModel;
final SharedTreeGraph sharedTreeGraph = treeBackedModel.convert(args.tree_number, args.tree_class);
assert sharedTreeGraph.subgraphArray.size() == 1;
sharedTreeSubgraph = sharedTreeGraph.subgraphArray.get(0);
if (! ((Model)possibleModel)._output.isClassifier()) {
args.tree_class = null; // Class may not be provided by the user, should be always filled correctly on output. NULL for regression.
}
} else {
final SharedTreeModel model = (SharedTreeModel) possibleModel;
final SharedTreeModel.SharedTreeOutput sharedTreeOutput = (SharedTreeModel.SharedTreeOutput) model._output;
final int treeClass = getResponseLevelIndex(args.tree_class, sharedTreeOutput);
sharedTreeSubgraph = model.getSharedTreeSubgraph(args.tree_number, treeClass);
// Class may not be provided by the user, should be always filled correctly on output. NULL for regression.
args.tree_class = sharedTreeOutput.isClassifier() ? sharedTreeOutput.classNames()[treeClass] : null;
}
final TreeProperties treeProperties = convertSharedTreeSubgraph(sharedTreeSubgraph, args.plain_language_rules);
args.left_children = treeProperties._leftChildren;
args.right_children = treeProperties._rightChildren;
args.descriptions = treeProperties._descriptions;
args.root_node_id = sharedTreeSubgraph.rootNode.getNodeNumber();
args.thresholds = treeProperties._thresholds;
args.features = treeProperties._features;
args.nas = treeProperties._nas;
args.levels = treeProperties.levels;
args.predictions = treeProperties._predictions;
args.tree_decision_path = treeProperties._treeDecisionPath;
args.decision_paths = treeProperties._decisionPaths;
return args;
}
private static String getLanguageRepresentation(SharedTreeSubgraph sharedTreeSubgraph) {
return getNodeRepresentation(sharedTreeSubgraph.rootNode, new StringBuilder(), 0).toString();
}
private static StringBuilder getNodeRepresentation(SharedTreeNode node, StringBuilder languageRepresentation, int padding) {
if (node.getRightChild() != null) {
languageRepresentation.append(getConditionLine(node, padding));
languageRepresentation.append(getNewPaddedLine(padding));
languageRepresentation = getNodeRepresentation(node.getRightChild(), languageRepresentation, padding +1);
languageRepresentation.append(getNewPaddedLine(padding));
languageRepresentation.append(getElseLine(node));
languageRepresentation.append(getNewPaddedLine(padding));
languageRepresentation = getNodeRepresentation(node.getLeftChild(), languageRepresentation, padding + 1);
languageRepresentation.append(getNewPaddedLine(padding));
languageRepresentation.append("}");
} else {
languageRepresentation.append(getNewPaddedLine(padding));
if (Float.compare(node.getPredValue(),Float.NaN) != 0) {
languageRepresentation.append("Predicted value: " + node.getPredValue());
} else {
languageRepresentation.append("Predicted value: NaN");
}
languageRepresentation.append(getNewPaddedLine(padding));
}
return languageRepresentation;
}
private static StringBuilder getNewPaddedLine(int padding) {
StringBuilder line = new StringBuilder("\n");
for(int i = 0; i < padding; i++) {
line.append("\t");
}
return line;
}
private static StringBuilder getElseLine(SharedTreeNode node) {
StringBuilder elseLine = new StringBuilder();
if (node.getDomainValues() == null) {
elseLine.append("} else {");
} else {
SharedTreeNode leftChild = node.getLeftChild();
elseLine.append("} else if ( ").append(node.getColName()).append(" is in [ ");
BitSet inclusiveLevelsSet = leftChild.getInclusiveLevels();
if (inclusiveLevelsSet != null) {
String stringToParseInclusiveLevelsFrom = inclusiveLevelsSet.toString();
int inclusiveLevelsLength = inclusiveLevelsSet.toString().length();
if (inclusiveLevelsLength > 2) {
// get rid of curly braces:
stringToParseInclusiveLevelsFrom = stringToParseInclusiveLevelsFrom.substring(1, inclusiveLevelsLength - 1);
String[] inclusiveLevels = stringToParseInclusiveLevelsFrom.split(",");
for (String index : inclusiveLevels) {
elseLine.append(node.getDomainValues()[Integer.parseInt(index.trim())] + " ");
}
} else {
elseLine.append("Missing set of levels for underlying node");
}
}
elseLine.append("]) {");
}
return elseLine;
}
private static StringBuilder getConditionLine(SharedTreeNode node, int padding) {
StringBuilder conditionLine = new StringBuilder();
if (padding != 0) {
conditionLine.append(getNewPaddedLine(padding));
}
if (node.getDomainValues() == null) {
if (Float.compare(node.getSplitValue(),Float.NaN) == 0) {
conditionLine.append("If ( " + node.getColName() + " is NaN ) {");
} else {
conditionLine.append("If ( " + node.getColName() + " >= " + node.getSplitValue());
if ("RIGHT".equals(getNaDirection(node))) {
conditionLine.append(" or ").append(node.getColName()).append(" is NaN ) {");
} else {
conditionLine.append(" ) {");
}
}
} else {
conditionLine.append("If ( " + node.getColName() + " is in [ ");
// get inclusive levels:
SharedTreeNode rightChild = node.getRightChild();
String stringToParseInclusiveLevelsFrom = rightChild.getInclusiveLevels().toString();
int inclusiveLevelsLength = rightChild.getInclusiveLevels().toString().length();
if (inclusiveLevelsLength > 2) {
// get rid of curly braces:
stringToParseInclusiveLevelsFrom = stringToParseInclusiveLevelsFrom.substring(1, inclusiveLevelsLength - 1);
String[] inclusiveLevels = stringToParseInclusiveLevelsFrom.split(",");
Arrays.stream(inclusiveLevels)
.map(String::trim)
.map(Integer::parseInt)
.forEach(index -> conditionLine.append(node.getDomainValues()[index] + " "));
} else {
conditionLine.append("Missing set of levels for underlying node");
}
conditionLine.append("]) {");
}
return conditionLine;
}
/**
* Converts H2O-3's internal representation of a tree in a form of {@link SharedTreeSubgraph} to a format
* expected by H2O clients.
*
* @param sharedTreeSubgraph An instance of {@link SharedTreeSubgraph} to convert
* @return An instance of {@link TreeProperties} with some attributes possibly empty if suitable. Never null.
*/
static TreeProperties convertSharedTreeSubgraph(final SharedTreeSubgraph sharedTreeSubgraph, PlainLanguageRules plainLanguageRules) {
Objects.requireNonNull(sharedTreeSubgraph);
final TreeProperties treeprops = new TreeProperties();
treeprops._leftChildren = MemoryManager.malloc4(sharedTreeSubgraph.nodesArray.size());
treeprops._rightChildren = MemoryManager.malloc4(sharedTreeSubgraph.nodesArray.size());
treeprops._descriptions = new String[sharedTreeSubgraph.nodesArray.size()];
treeprops._thresholds = MemoryManager.malloc4f(sharedTreeSubgraph.nodesArray.size());
treeprops._features = new String[sharedTreeSubgraph.nodesArray.size()];
treeprops._nas = new String[sharedTreeSubgraph.nodesArray.size()];
treeprops._predictions = MemoryManager.malloc4f(sharedTreeSubgraph.nodesArray.size());
treeprops._leafNodeAssignments = new String[sharedTreeSubgraph.nodesArray.size()];
treeprops._decisionPaths = new String[sharedTreeSubgraph.nodesArray.size()];
treeprops._leftChildrenNormalized = MemoryManager.malloc4(sharedTreeSubgraph.nodesArray.size());
treeprops._rightChildrenNormalized = MemoryManager.malloc4(sharedTreeSubgraph.nodesArray.size());
// Set root node's children, there is no guarantee the root node will be number 0
treeprops._rightChildren[0] = sharedTreeSubgraph.rootNode.getRightChild() != null ? sharedTreeSubgraph.rootNode.getRightChild().getNodeNumber() : -1;
treeprops._leftChildren[0] = sharedTreeSubgraph.rootNode.getLeftChild() != null ? sharedTreeSubgraph.rootNode.getLeftChild().getNodeNumber() : -1;
treeprops._thresholds[0] = sharedTreeSubgraph.rootNode.getSplitValue();
treeprops._features[0] = sharedTreeSubgraph.rootNode.getColName();
treeprops._nas[0] = getNaDirection(sharedTreeSubgraph.rootNode);
treeprops.levels = new int[sharedTreeSubgraph.nodesArray.size()][];
if (plainLanguageRules.equals(PlainLanguageRules.AUTO)) {
/* 255 = number of nodes for complete binary tree of depth 7 (2^(k+1)−1) */
plainLanguageRules = sharedTreeSubgraph.nodesArray.size() < 256 ? PlainLanguageRules.TRUE : PlainLanguageRules.FALSE;
}
if (plainLanguageRules.equals(PlainLanguageRules.TRUE)) {
treeprops._treeDecisionPath = getLanguageRepresentation(sharedTreeSubgraph);
treeprops._decisionPaths[0] = "Predicted value: " + sharedTreeSubgraph.rootNode.getPredValue();
treeprops._leftChildrenNormalized[0] = sharedTreeSubgraph.rootNode.getLeftChild() != null ? sharedTreeSubgraph.rootNode.getLeftChild().getNodeNumber() : -1;
treeprops._rightChildrenNormalized[0] = sharedTreeSubgraph.rootNode.getRightChild() != null ? sharedTreeSubgraph.rootNode.getRightChild().getNodeNumber() : -1;
}
treeprops._domainValues = new String[sharedTreeSubgraph.nodesArray.size()][];
treeprops._domainValues[0] = sharedTreeSubgraph.rootNode.getDomainValues();
List<SharedTreeNode> nodesToTraverse = new ArrayList<>();
nodesToTraverse.add(sharedTreeSubgraph.rootNode);
append(treeprops._rightChildren, treeprops._leftChildren,
treeprops._descriptions, treeprops._thresholds, treeprops._features, treeprops._nas,
treeprops.levels, treeprops._predictions, nodesToTraverse, -1, false, treeprops._domainValues);
if (plainLanguageRules.equals(PlainLanguageRules.TRUE)) fillLanguagePathRepresentation(treeprops, sharedTreeSubgraph.rootNode);
return treeprops;
}
private static void append(final int[] rightChildren, final int[] leftChildren, final String[] nodesDescriptions,
final float[] thresholds, final String[] splitColumns, final String[] naHandlings,
final int[][] levels, final float[] predictions,
final List<SharedTreeNode> nodesToTraverse, int pointer, boolean visitedRoot,
String[][] domainValues) {
if(nodesToTraverse.isEmpty()) return;
List<SharedTreeNode> discoveredNodes = new ArrayList<>();
for (SharedTreeNode node : nodesToTraverse) {
pointer++;
final SharedTreeNode leftChild = node.getLeftChild();
final SharedTreeNode rightChild = node.getRightChild();
if(visitedRoot){
fillnodeDescriptions(node, nodesDescriptions, thresholds, splitColumns, levels, predictions,
naHandlings, pointer, domainValues);
} else {
StringBuilder rootDescriptionBuilder = new StringBuilder();
rootDescriptionBuilder.append("*** WARNING: This property is deprecated! *** ");
rootDescriptionBuilder.append("Root node has id ");
rootDescriptionBuilder.append(node.getNodeNumber());
rootDescriptionBuilder.append(" and splits on column '");
rootDescriptionBuilder.append(node.getColName());
rootDescriptionBuilder.append("'. ");
fillNodeSplitTowardsChildren(rootDescriptionBuilder, node);
nodesDescriptions[pointer] = rootDescriptionBuilder.toString();
visitedRoot = true;
}
if (leftChild != null) {
discoveredNodes.add(leftChild);
leftChildren[pointer] = leftChild.getNodeNumber();
} else {
leftChildren[pointer] = NO_CHILD;
}
if (rightChild != null) {
discoveredNodes.add(rightChild);
rightChildren[pointer] = rightChild.getNodeNumber();
} else {
rightChildren[pointer] = NO_CHILD;
}
}
append(rightChildren, leftChildren, nodesDescriptions, thresholds, splitColumns, naHandlings, levels, predictions,
discoveredNodes, pointer, true, domainValues);
}
private static List<Integer> extractInternalIds(TreeProperties properties) {
int nodeId = 0;
List<Integer> nodeIds = new ArrayList<>();
nodeIds.add(nodeId);
for (int i = 0; i < properties._leftChildren.length; i++) {
if (properties._leftChildren[i] != -1) {
nodeId++;
nodeIds.add(properties._leftChildren[i]);
properties._leftChildrenNormalized[i] = nodeId;
} else {
properties._leftChildrenNormalized[i] = -1;
}
if (properties._rightChildren[i] != -1) {
nodeId++;
nodeIds.add(properties._rightChildren[i]);
properties._rightChildrenNormalized[i] = nodeId;
} else {
properties._rightChildrenNormalized[i] = -1;
}
}
return nodeIds;
}
static String getCondition(SharedTreeNode node, String from) {
StringBuilder sb = new StringBuilder();
if (node.getDomainValues() != null) {
sb.append("If (");
sb.append(node.getColName());
sb.append(" is in [");
BitSet inclusiveLevels;
if (from.equals("R")) {
inclusiveLevels = node.getLeftChild().getInclusiveLevels();
} else {
inclusiveLevels = node.getRightChild().getInclusiveLevels();
}
if (inclusiveLevels != null) {
String stringToParseInclusiveLevelsFrom = inclusiveLevels.toString();
int inclusiveLevelsLength = stringToParseInclusiveLevelsFrom.length();
if (inclusiveLevelsLength > 2) {
stringToParseInclusiveLevelsFrom = stringToParseInclusiveLevelsFrom.substring(1, inclusiveLevelsLength - 1);
String[] inclusiveLevelsStr = stringToParseInclusiveLevelsFrom.split(",");
for (String level : inclusiveLevelsStr) {
sb.append(node.getDomainValues()[Integer.parseInt(level.replaceAll("\\s", ""))]).append(" ");
}
}
} else {
sb.append(" ");
}
sb.append("]) -> ");
} else {
if (Float.compare(node.getSplitValue(), Float.NaN) == 0) {
String sign;
if ("R".equals(from)) {
sign = " is not ";
} else {
sign = " is ";
}
sb.append("If ( ").append(node.getColName()).append(sign).append("NaN )");
} else {
String sign;
boolean useNan = false;
String nanString = " or " + node.getColName() + " is NaN";
if ("R".equals(from)) {
sign = " < ";
if (node.getLeftChild().isInclusiveNa()) {
useNan = true;
}
} else {
sign = " >= ";
if (node.getRightChild().isInclusiveNa()) {
useNan = true;
}
}
sb.append("If ( " ).append(node.getColName()).append(sign).append(node.getSplitValue());
if (useNan) {
sb.append(nanString);
}
sb.append(" ) -> ");
}
}
return sb.toString();
}
private static List<PathResult> findPaths(SharedTreeNode node) {
if (node == null)
return new ArrayList<>();
List<PathResult> result = new ArrayList<>();
List<PathResult> leftSubtree = findPaths(node.getLeftChild());
List<PathResult> rightSubtree = findPaths(node.getRightChild());
for (int i = 0; i < leftSubtree.size(); i++){
PathResult leftResult = leftSubtree.get(i);
PathResult newResult = leftResult;
newResult.path.insert(0, getCondition(node, "R"));
result.add(newResult);
}
for (int i = 0; i < rightSubtree.size(); i++){
PathResult rightResult = rightSubtree.get(i);
PathResult newResult = rightResult;
newResult.path.insert(0, getCondition(node, "L"));
result.add(newResult);
}
if (result.size() == 0) {
result.add(new PathResult(node.getNodeNumber()));
result.get(0).path.append("Prediction: ").append(node.getPredValue());
}
return result;
}
private static void fillLanguagePathRepresentation(TreeProperties properties, SharedTreeNode root) {
List<Integer> nodeIds = extractInternalIds(properties);
List<PathResult> paths = findPaths(root);
for (PathResult path : paths) {
properties._decisionPaths[nodeIds.indexOf(path.nodeId)] = path.path.toString();
}
}
private static void fillnodeDescriptions(final SharedTreeNode node, final String[] nodeDescriptions,
final float[] thresholds, final String[] splitColumns, final int[][] levels,
final float[] predictions, final String[] naHandlings, final int pointer, final String[][] domainValues) {
final StringBuilder nodeDescriptionBuilder = new StringBuilder();
int[] nodeLevels = node.getParent().isBitset() ? extractNodeLevels(node) : null;
nodeDescriptionBuilder.append("*** WARNING: This property is deprecated! *** ");
nodeDescriptionBuilder.append("Node has id ");
nodeDescriptionBuilder.append(node.getNodeNumber());
if (node.getColName() != null && node.isLeaf()) {
nodeDescriptionBuilder.append(" and splits on column '");
nodeDescriptionBuilder.append(node.getColName());
nodeDescriptionBuilder.append("'. ");
} else {
nodeDescriptionBuilder.append(" and is a terminal node. ");
}
fillNodeSplitTowardsChildren(nodeDescriptionBuilder, node);
if (!Float.isNaN(node.getParent().getSplitValue())) {
nodeDescriptionBuilder.append(" Parent node split threshold is ");
nodeDescriptionBuilder.append(node.getParent().getSplitValue());
nodeDescriptionBuilder.append(". Prediction: ");
nodeDescriptionBuilder.append(node.getPredValue());
nodeDescriptionBuilder.append(".");
} else if (node.getParent().isBitset()) {
nodeLevels = extractNodeLevels(node);
nodeDescriptionBuilder.append(" Parent node split on column [");
nodeDescriptionBuilder.append(node.getParent().getColName());
if(nodeLevels != null) {
nodeDescriptionBuilder.append("]. Inherited categorical levels from parent split: ");
for (int nodeLevelsindex = 0; nodeLevelsindex < nodeLevels.length; nodeLevelsindex++) {
nodeDescriptionBuilder.append(node.getParent().getDomainValues()[nodeLevels[nodeLevelsindex]]);
if (nodeLevelsindex != nodeLevels.length - 1) nodeDescriptionBuilder.append(",");
}
} else {
nodeDescriptionBuilder.append("]. No categoricals levels inherited from parent.");
}
} else {
nodeDescriptionBuilder.append("Split value is NA.");
}
nodeDescriptions[pointer] = nodeDescriptionBuilder.toString();
splitColumns[pointer] = node.getColName();
naHandlings[pointer] = getNaDirection(node);
levels[pointer] = nodeLevels;
predictions[pointer] = node.getPredValue();
thresholds[pointer] = node.getSplitValue();
domainValues[pointer] = node.getDomainValues();
}
private static void fillNodeSplitTowardsChildren(final StringBuilder nodeDescriptionBuilder, final SharedTreeNode node){
if (!Float.isNaN(node.getSplitValue())) {
nodeDescriptionBuilder.append("Split threshold is ");
if (node.getLeftChild() != null) {
nodeDescriptionBuilder.append(" < ");
nodeDescriptionBuilder.append(node.getSplitValue());
nodeDescriptionBuilder.append(" to the left node (");
nodeDescriptionBuilder.append(node.getLeftChild().getNodeNumber());
nodeDescriptionBuilder.append(")");
}
if (node.getLeftChild() != null) {
if(node.getLeftChild() != null) nodeDescriptionBuilder.append(", ");
nodeDescriptionBuilder.append(" >= ");
nodeDescriptionBuilder.append(node.getSplitValue());
nodeDescriptionBuilder.append(" to the right node (");
nodeDescriptionBuilder.append(node.getRightChild().getNodeNumber());
nodeDescriptionBuilder.append(")");
}
nodeDescriptionBuilder.append(".");
} else if (node.isBitset()) {
fillNodeCategoricalSplitDescription(nodeDescriptionBuilder, node);
}
}
private static int[] extractNodeLevels(final SharedTreeNode node) {
final BitSet childInclusiveLevels = node.getInclusiveLevels();
final int cardinality = childInclusiveLevels.cardinality();
if (cardinality > 0) {
int[] nodeLevels = MemoryManager.malloc4(cardinality);
int bitsignCounter = 0;
for (int i = childInclusiveLevels.nextSetBit(0); i >= 0; i = childInclusiveLevels.nextSetBit(i + 1)) {
nodeLevels[bitsignCounter] = i;
bitsignCounter++;
}
return nodeLevels;
}
return null;
}
private static void fillNodeCategoricalSplitDescription(final StringBuilder nodeDescriptionBuilder, final SharedTreeNode node) {
final SharedTreeNode leftChild = node.getLeftChild();
final SharedTreeNode rightChild = node.getRightChild();
final int[] leftChildLevels = extractNodeLevels(leftChild);
final int[] rightChildLevels = extractNodeLevels(rightChild);
if (leftChild != null) {
nodeDescriptionBuilder.append(" Left child node (");
nodeDescriptionBuilder.append(leftChild.getNodeNumber());
nodeDescriptionBuilder.append(") inherits categorical levels: ");
if (leftChildLevels != null) {
for (int nodeLevelsindex = 0; nodeLevelsindex < leftChildLevels.length; nodeLevelsindex++) {
nodeDescriptionBuilder.append(node.getDomainValues()[leftChildLevels[nodeLevelsindex]]);
if (nodeLevelsindex != leftChildLevels.length - 1) nodeDescriptionBuilder.append(",");
}
}
}
if (rightChild != null) {
nodeDescriptionBuilder.append(". Right child node (");
nodeDescriptionBuilder.append(rightChild.getNodeNumber());
nodeDescriptionBuilder.append(") inherits categorical levels: ");
if (rightChildLevels != null) {
for (int nodeLevelsindex = 0; nodeLevelsindex < rightChildLevels.length; nodeLevelsindex++) {
nodeDescriptionBuilder.append(node.getDomainValues()[rightChildLevels[nodeLevelsindex]]);
if (nodeLevelsindex != rightChildLevels.length - 1) nodeDescriptionBuilder.append(",");
}
}
}
nodeDescriptionBuilder.append(". ");
}
private static String getNaDirection(final SharedTreeNode node) {
final boolean leftNa = node.getLeftChild() != null && node.getLeftChild().isInclusiveNa();
final boolean rightNa = node.getRightChild() != null && node.getRightChild().isInclusiveNa();
assert (rightNa ^ leftNa) || (rightNa == false && leftNa == false);
if (leftNa) {
return "LEFT";
} else if (rightNa) {
return "RIGHT";
}
return null; // No direction
}
public static class TreeProperties {
public int[] _leftChildren;
public int[] _rightChildren;
public String[] _descriptions; // General node description, most likely to contain serialized threshold or inclusive dom. levels
public float[] _thresholds;
public String[] _features;
public int[][] levels; // Categorical levels, points to a list of categoricals that is already existing within the model on the client.
public String[] _nas;
public float[] _predictions; // Prediction values on terminal nodes
public String _treeDecisionPath;
public String[] _leafNodeAssignments;
public String[] _decisionPaths;
private int[] _leftChildrenNormalized;
private int[] _rightChildrenNormalized;
private String[][] _domainValues;
}
}
| h2oai/h2o-3 | h2o-algos/src/main/java/hex/tree/TreeHandler.java |
45,357 | package gr.aueb.cf.ch2;
public class TypecastApp {
public static void main(String[] args) {
int num1 = 10;
long num2 = 20L;
long result = 0L;
num1 = (int) num2; //τα typecast είναι error prone, να τα αποφεύγουμε.
result = (long) num1 + num2; //περιττό μετατρέπεται αυτόματα
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch2/TypecastApp.java |
45,406 | package cn.originx.refine;
import io.vertx.core.json.JsonArray;
import io.vertx.up.eon.em.ChangeFlag;
import io.vertx.up.log.Annal;
import io.vertx.up.log.Log;
import java.util.concurrent.ConcurrentMap;
/**
* ## 「内部」日志器
*
* ### 1. 基本介绍
*
* Ox平台专用内部日志器(部分方法内部调用)
*
* ### 2. 日志器种类
*
* - Hub日志器
* - Shell日志器
* - Compare比较日志器
*
* @author <a href="http://www.origin-x.cn">Lang</a>
*/
final class OxLog {
/*
* 私有构造函数(工具类转换)
*/
private OxLog() {
}
/**
* INFO日志处理
*
* @param logger {@link Annal} Zero专用日志器
* @param flag {@link String} 业务标记
* @param pattern {@link String} 日志信息模式
* @param args {@link Object...} 可变参数
*/
static void info(final Annal logger,
final String flag, final String pattern, final Object... args) {
logger.info(Log.green("Προέλευση Χ") + " ( " + flag + " ) " + pattern, args);
}
/**
* DEBUG日志处理
*
* @param logger {@link Annal} Zero专用日志器
* @param flag {@link String} 业务标记
* @param pattern {@link String} 日志信息模式
* @param args {@link Object...} 可变参数
*/
static void debug(final Annal logger,
final String flag, final String pattern, final Object... args) {
logger.debug(Log.green("Προέλευση Χ") + " ( " + flag + " ) " + pattern, args);
}
/**
* WARN日志处理
*
* @param logger {@link Annal} Zero专用日志器
* @param flag {@link String} 业务标记
* @param pattern {@link String} 日志信息模式
* @param args {@link Object...} 可变参数
*/
static void warn(final Annal logger,
final String flag, final String pattern, final Object... args) {
logger.warn(Log.green("Προέλευση Χ") + " ( " + flag + " ) " + pattern, args);
}
/**
* Info级别,Hub专用日志器(内部和外部)
*
* @param logger {@link Annal} Zero专用日志器
* @param pattern {@link String} 日志信息模式
* @param args {@link Object...} 可变参数
*/
static void infoHub(final Annal logger, final String pattern, final Object... args) {
OxLog.info(logger, "Hub", pattern, args);
}
/**
* Info级别,Hub专用日志器(内部和外部)
*
* @param clazz {@link Class} 调用日志器的类
* @param pattern {@link String} 日志信息模式
* @param args {@link Object...} 可变参数
*/
static void infoHub(final Class<?> clazz, final String pattern, final Object... args) {
final Annal logger = Annal.get(clazz);
infoHub(logger, pattern, args);
}
/**
* Warn级别,Hub专用日志器(内部和外部)
*
* @param logger {@link Annal} Zero专用日志器
* @param pattern {@link String} 日志信息模式
* @param args {@link Object...} 可变参数
*/
static void warnHub(final Annal logger, final String pattern, final Object... args) {
OxLog.warn(logger, "Hub", pattern, args);
}
/**
* Info级别,Shell专用日志器(内部和外部)
*
* @param logger {@link Annal} Zero专用日志器
* @param pattern {@link String} 日志信息模式
* @param args {@link Object...} 可变参数
*/
static void warnShell(final Annal logger, final String pattern, final Object... args) {
OxLog.warn(logger, "Shell", pattern, args);
}
/**
* Warn级别,Hub专用日志器(内部和外部)
*
* @param clazz {@link Class} 调用日志器的类
* @param pattern {@link String} 日志信息模式
* @param args {@link Object...} 可变参数
*/
static void warnHub(final Class<?> clazz, final String pattern, final Object... args) {
final Annal logger = Annal.get(clazz);
warnHub(logger, pattern, args);
}
/**
* Info级别,比较结果日志
*
* @param clazz {@link Class} 调用日志器的类
* @param map 比对结果表
*/
static void infoCompared(final Class<?> clazz, final ConcurrentMap<ChangeFlag, JsonArray> map) {
final Annal logger = Annal.get(clazz);
OxLog.info(logger, "CRT", "Report Start ----- ");
map.forEach((type, data) -> OxLog.info(logger, "CRT", "Type = {0}, Size = {2}, Data = {1}",
type, data.encode(), String.valueOf(data.size())));
OxLog.info(logger, "CRT", "Report End ----- ");
}
}
| himozhang/vertx-zero | vertx-pin/zero-vie/src/main/java/cn/originx/refine/OxLog.java |
45,412 | package io.mature.extension.refine;
import cn.vertxup.ambient.domain.tables.pojos.XActivity;
import cn.vertxup.ambient.service.application.AppStub;
import cn.vertxup.ambient.service.application.InitStub;
import cn.vertxup.workflow.domain.tables.pojos.WTodo;
import io.horizon.eon.em.Environment;
import io.horizon.eon.em.typed.ChangeFlag;
import io.horizon.spi.plugin.AfterPlugin;
import io.horizon.spi.plugin.AspectPlugin;
import io.horizon.uca.log.Log;
import io.horizon.uca.log.LogModule;
import io.mature.extension.cv.em.TypeLog;
import io.mature.extension.uca.code.Numeration;
import io.mature.stellar.ArgoStore;
import io.modello.atom.app.KIntegration;
import io.modello.atom.normalize.KIdentity;
import io.modello.specification.HRecord;
import io.modello.specification.action.HDao;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.mod.atom.modeling.builtin.DataAtom;
import io.vertx.mod.atom.modeling.data.DataGroup;
import io.vertx.up.unity.Ux;
import io.vertx.up.util.Ut;
import io.zerows.core.cloud.eon.VDBC;
import io.zerows.core.feature.database.cp.zdk.DataPool;
import io.zerows.core.web.metadata.commune.Envelop;
import io.zerows.plugins.store.elasticsearch.ElasticSearchClient;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* ## 统一工具类
*
* 可在环境中直接使用`Ox.xxx`的方式调用工具类。
*
* ### 1. 内置工具类列表
*
* |类名|说明|
* |:---|:---|
* |{@link OxAmbient}|环境工具|
* |{@link OxCompareUi}|界面比对工具|
* |{@link OxConfig}|环境配置工具|
* |{@link OxConsole}|命令行工具|
* |{@link OxTo}|数据工具|
* |{@link OxField}|字段工具|
* |{@link OxJson}|Json处理工具|
* |{@link OxMocker}|数据模拟工具|
* |{@link OxPlugin}|插件工具|
* |{@link OxView}|视图工具|
*
* @author <a href="http://www.origin-x.cn">Lang</a>
*/
@SuppressWarnings("all")
public final class Ox {
/**
* ## 日志器
*
* ### 1. 基本介绍
*
* Ox平台专用内部日志器,外部日志器。
*
* ### 2. 日志器种类
*
* - Atom模型日志器
* - UCA日志器
* - Shell日志器
* - 插件Plugin日志器
* - Hub总线日志器
* - Web流程日志器
* - 状态日志器
*/
private static ConcurrentMap<Class<?>, String> NUM_MAP = new ConcurrentHashMap<Class<?>, String>() {
{
this.put(XActivity.class, "NUM.ACTIVITY");
this.put(WTodo.class, "NUM.TODO");
}
};
/*
* 私有构造函数(工具类转换)
*/
private Ox() {
}
public static void numerationStd() {
Numeration.preprocess(NUM_MAP);
}
public static Future<HRecord> viGet(final DataAtom atom, final String identifier,
final String field, final Object value) {
return OxLinker.viGet(atom, identifier, field, value);
}
public static Future<HRecord[]> viGet(final DataAtom atom, final String identifier,
final String field, final JsonArray values) {
return OxLinker.viGet(atom, identifier, field, values);
}
public static Future<ConcurrentMap<String, HRecord>> viGetMap(final DataAtom atom, final String identifier,
final String field, final JsonArray values) {
return OxLinker.viGetMap(atom, identifier, field, values, field);
}
public static Future<ConcurrentMap<String, HRecord>> viGetMap(final DataAtom atom, final String identifier,
final String field, final JsonArray values,
final String fieldGroup) {
return OxLinker.viGetMap(atom, identifier, field, values, fieldGroup);
}
/**
* 「After」读取<value>plugin.ticket</value>值提取ITSM开单专用插件。
*
* @param options {@link JsonObject} ServiceConfig配置原始数据
*
* @return {@link AfterPlugin}
*/
public static AfterPlugin pluginTicket(final JsonObject options) {
return Ut.plugin(options, VDBC.I_SERVICE.SERVICE_CONFIG.PLUGIN_TICKET, AfterPlugin.class);
}
/**
* 「Around」读取<value>plugin.activity</value>值构造历史记录生成专用插件。
*
* @param options {@link JsonObject} ServiceConfig配置原始数据
*
* @return {@link AspectPlugin}
*/
public static AspectPlugin pluginActivity(final JsonObject options) {
return Ut.plugin(options, VDBC.I_SERVICE.SERVICE_CONFIG.PLUGIN_ACTIVITY, AspectPlugin.class);
}
/**
* 「Around」读取<value>plugin.todo</value>值构造待办确认单生成专用插件。
*
* @param options {@link JsonObject} ServiceConfig配置原始数据
*
* @return {@link AspectPlugin}
*/
public static AspectPlugin pluginTodo(final JsonObject options) {
return Ut.plugin(options, VDBC.I_SERVICE.SERVICE_CONFIG.PLUGIN_TODO, AspectPlugin.class);
}
/**
* 「Around」读取<value>plugin.component</value>值构造标准的AOP插件,执行Before和After两个核心流程
*
* - <value>plugin.component.before</value>:前置插件表(数组)
* - <value>plugin.component.after</value>:后置插件表(数组)
*
* @param options {@link JsonObject} ServiceConfig配置原始数据
*
* @return {@link AspectPlugin}
*/
public static AspectPlugin pluginComponent(final JsonObject options) {
return Ut.plugin(options, VDBC.I_SERVICE.SERVICE_CONFIG.PLUGIN_COMPONENT, AspectPlugin.class);
}
/**
* 构造标识规则选择器,读取插件<value>plugin.identifier</value>值提取标识规则选择器,使用默认配置项`options`。
*
* @param atom {@link DataAtom} 模型定义
*
* @return {@link KIdentity} 构造好的标识规则选择器
*/
public static KIdentity pluginIdentifier(final DataAtom atom) {
return OxConfig.toIdentity(atom, ArgoStore.options());
}
/**
* 构造初始化专用接口,用于初始化某个`X_APP`的应用配置。
*
* - 初始化接口{@link InitStub},执行应用初始化。
* - 应用访问接口{@link AppStub}。
*
* @return {@link InitStub}
*/
public static InitStub pluginInitializer() {
return OxAmbient.pluginInitializer();
}
/**
* 读取前置插件链:`plugin.component.before`。
*
* @param options {@link JsonObject} 服务配置数据,对应ServiceConfig字段
*
* @return {@link List}<{@link Class}>
*/
public static List<Class<?>> pluginBefore(final JsonObject options) {
return OxAmbient.pluginClass(options, VDBC.I_SERVICE.SERVICE_CONFIG.PLUGIN_COMPONENT_BEFORE);
}
/**
* 读取后置插件链:`plugin.component.after`。
*
* @param options {@link JsonObject} 服务配置数据,对应ServiceConfig字段
*
* @return {@link List}<{@link Class}>
*/
public static List<Class<?>> pluginAfter(final JsonObject options) {
return OxAmbient.pluginClass(options, VDBC.I_SERVICE.SERVICE_CONFIG.PLUGIN_COMPONENT_AFTER);
}
/**
* 读取后置异步插件:`plugin.component.job`。
*
* @param options {@link JsonObject} 服务配置数据,对应ServiceConfig字段
*
* @return {@link List}<{@link Class}>
*/
public static List<Class<?>> pluginJob(final JsonObject options) {
return OxAmbient.pluginClass(options, VDBC.I_SERVICE.SERVICE_CONFIG.PLUGIN_COMPONENT_JOB);
}
/**
* 从原始配置数据中读取`plugin.config`节点,根据传入的`clazz`读取和当前插件相关的配置信息。
*
* - 从原始配置中读取基础配置,上层传入的`options`数据。
* - 提取`plugin.config`中和`clazz`绑定的配置数据。
* - 合并二者所有配置数据构造最终配置数据。
*
* @param clazz {@link Class} 执行初始化的类信息,反射调用
* @param options {@link JsonObject} 服务配置数据,对应ServiceConfig字段
*
* @return {@link JsonObject}
*/
public static JsonObject pluginOptions(final Class<?> clazz, final JsonObject options) {
return OxAmbient.pluginOptions(clazz, options);
}
/**
* 切面执行器,执行`before -> executor -> after`流程处理数据记录。
*
* @param input {@link JsonObject} 输入数据记录
* @param config {@link JsonObject} 配置数据
* @param supplier {@link Supplier} 插件提取器,提取{@link AspectPlugin}插件
* @param atom {@link DataAtom} 模型定义
* @param executor {@link Function} 函数执行器
*
* @return 返回执行的最终结果{@link io.vertx.core.Future}<{@link JsonObject}>
*/
public static Future<JsonObject> runAop(final JsonObject input, final JsonObject config,
final Supplier<AspectPlugin> supplier, final DataAtom atom,
final Function<JsonObject, Future<JsonObject>> executor) {
return OxPlugin.runAop(input, config, supplier, atom, executor);
}
/**
* 数据源执行器,{@link DataPool}数据源运行主流程。
*
* @param sigma {@link String} 应用统一标识符
* @param supplier {@link Supplier} 外部数据读取器
* @param executor {@link Function} 函数执行器
* @param <T> 最终执行后返回的数据类型
*
* @return {@link Future}
*/
public static <T> Future<T> runDs(final String sigma, final Supplier<T> supplier,
final Function<DataPool, Future<T>> executor) {
return OxPlugin.runDs(sigma, supplier, executor);
}
/**
* 分组运行器,将数据分组后执行分组过后的运行。
*
* - 每一组有相同的模型定义{@link DataAtom}。
* - 每一组有相同的数据输入{@link JsonArray}
*
* @param groupSet {@link Set}<{@link DataGroup}> 分组集合
* @param consumer {@link BiFunction} 双输入函数
*
* @return {@link Future}<{@link JsonArray}>
*/
public static Future<JsonArray> runGroup(final Set<DataGroup> groupSet,
final BiFunction<JsonArray, DataAtom, Future<JsonArray>> consumer) {
return OxPlugin.runGroup(groupSet, consumer);
}
/**
* 「Function」插件类安全执行器,执行内部`executor`,若有异常则直接调用内部日志记录。
*
* @param clazz {@link Class} 调用该方法的对象类
* @param input `executor`的输入
* @param executor {@link Function} 外部传入执行器
* @param <T> `executor`执行器处理类型
*
* @return `executor`执行结果
*/
public static <T> Future<T> runSafe(final Class<?> clazz, final T input, final Function<T, Future<T>> executor) {
return OxPlugin.runSafe(clazz, input, executor);
}
/**
* 「Supplier」插件类安全执行器,执行内部`executor`,若有异常则直接调用内部日志记录。
*
* @param clazz {@link Class} 调用该方法的对象类
* @param input `executor`的输入
* @param supplier {@link Supplier} 外部传入数据构造器
* @param <T> `executor`执行器处理类型
*
* @return `executor`执行结果
*/
public static <T> Future<T> runSafe(final Class<?> clazz, final T input, final Supplier<T> supplier) {
return OxPlugin.runSafe(clazz, input, supplier);
}
/**
* 命令执行器,批量调用操作系统中的命令提示符运行操作命令。
*
* @param commands {@link List}<{@link String}> 待执行的命令清单
*/
public static void runCmd(final List<String> commands) {
OxConsole.runCmd(commands);
}
/**
* 「Async」ElasticSearch异步执行器,重建索引。
*
* @param atom {@link DataAtom} 模型定义
*
* @return {@link Future}<{@link ElasticSearchClient}>
*/
public static Future<ElasticSearchClient> runEs(final DataAtom atom) {
return OxConsole.runEs(atom);
}
/**
* {@link JsonObject}模拟数据
*
* @param integration {@link KIntegration} 集成配置对象
* @param file {@link String} 模拟数据读取文件
* @param supplier {@link Supplier} 真实执行器
*
* @return {@link JsonObject} 返回最终数据记录
*/
public static JsonObject mockJ(final KIntegration integration, final String file, final Supplier<JsonObject> supplier) {
return OxMocker.mockJ(integration, file, supplier);
}
/**
* {@link JsonArray}模拟数据
*
* @param integration {@link KIntegration} 集成配置对象
* @param file {@link String} 模拟数据读取文件
* @param supplier {@link Supplier} 真实执行器
*
* @return {@link JsonArray} 返回最终数据记录
*/
public static JsonArray mockA(final KIntegration integration, final String file, final Supplier<JsonArray> supplier) {
return OxMocker.mockA(integration, file, supplier);
}
/**
* {@link String}模拟数据
*
* @param integration {@link KIntegration} 集成配置对象
* @param file {@link String} 模拟数据读取文件
* @param supplier {@link Supplier} 真实执行器
*
* @return {@link String} 返回最终数据记录
*/
public static String mockS(final KIntegration integration, final String file, final Supplier<String> supplier) {
return OxMocker.mockS(integration, file, supplier);
}
/**
* 「Async」{@link JsonObject}模拟数据
*
* @param integration {@link KIntegration} 集成配置对象
* @param file {@link String} 模拟数据读取文件
* @param supplier {@link Supplier} 真实执行器
*
* @return {@link JsonObject} 返回最终数据记录
*/
public static Future<JsonObject> mockAsyncJ(final KIntegration integration, final String file, final Supplier<Future<JsonObject>> supplier) {
return OxMocker.mockAsyncJ(integration, file, supplier);
}
/**
* 「Async」{@link JsonArray}模拟数据
*
* @param integration {@link KIntegration} 集成配置对象
* @param file {@link String} 模拟数据读取文件
* @param supplier {@link Supplier} 真实执行器
*
* @return {@link JsonArray} 返回最终数据记录
*/
public static Future<JsonArray> mockAsyncA(final KIntegration integration, final String file, final Supplier<Future<JsonArray>> supplier) {
return OxMocker.mockAsyncA(integration, file, supplier);
}
/**
* 「Async」{@link String}模拟数据
*
* @param integration {@link KIntegration} 集成配置对象
* @param file {@link String} 模拟数据读取文件
* @param supplier {@link Supplier} 真实执行器
*
* @return {@link String} 返回最终数据记录
*/
public static Future<String> mockAsyncS(final KIntegration integration, final String file, final Supplier<Future<String>> supplier) {
return OxMocker.mockAsyncS(integration, file, supplier);
}
/**
* 基本平台级忽略字段
*
* @param atom {@link DataAtom}
*
* @return {@link Set}
*/
public static Set<String> ignorePure(final DataAtom atom) {
return OxField.ignorePure(atom);
}
/**
* syncIn = false 的忽略字段
*
* @param atom {@link DataAtom}
*
* @return {@link Set}
*/
public static Set<String> ignoreIn(final DataAtom atom) {
return OxField.ignoreIn(atom);
}
/**
* 从第三方拉取数据的忽略字段
*
* @param atom {@link DataAtom}
*
* @return {@link Set}
*/
public static Set<String> ignorePull(final DataAtom atom) {
return OxField.ignorePull(atom);
}
/**
* 开放API部分的忽略字段
*
* @param atom {@link DataAtom}
*
* @return {@link Set}
*/
public static Set<String> ignoreApi(final DataAtom atom) {
return OxField.ignoreApi(atom);
}
/**
* 推送过程中的忽略字段
*
* @param atom {@link DataAtom}
*
* @return {@link Set}
*/
public static Set<String> ignorePush(final DataAtom atom) {
return OxField.ignorePush(atom);
}
/**
* 将输入数据构造成集合{@link Set}<{@link DataGroup}>封装对象。
*
* {@link DataGroup}中包含了三个核心数据:
*
* - 数据部分:{@link JsonArray}数据信息。
* - identifier:{@link String}模型标识符。
* - 元数据部分:{@link DataAtom} 模型定义对象。
*
* @param atom {@link DataAtom} 模型定义
* @param input {@link JsonArray} 数据信息
*
* @return {@link Set}<{@link DataGroup}>
*/
public static Set<DataGroup> toGroup(final DataAtom atom, final JsonArray input) {
final Set<DataGroup> set = new HashSet<>();
set.add(DataGroup.create(atom).add(input));
return set;
}
/**
* 根据传入路径执行路径解析工作,解析三种不同环境的路径。
*
* - Development:开发环境
* - Production:生产环境
* - Mockito:模拟测试环境(integration中的debug = true)
*
* @param path {@link String} 构造的环境读取数据专用路径
* @param environment {@link Environment} 传入环境数据
*
* @return {@link String} 返回不同环境处理过的绝对路径信息
*/
public static String toRoot(final String path, final Environment environment) {
return OxAmbient.resolve(path, environment);
}
/**
* 根据传入路径执行解析工作,解析`Development`开发环境的路径。
*
* @param path {@link String} 构造的环境读取数据专用路径
*
* @return {@link String} 返回不同环境处理过的绝对路径信息
*/
public static String toRootDev(final String path) {
return OxAmbient.resolve(path, Environment.Development);
}
/**
* 「Async」元数据执行器
*
* @param input 输入的最终响应数据,内部调用`metadata(JsonArray)`方法执行转换。
*
* @return {@link Future}<{@link JsonArray}> 异步执行结果
*/
public static Future<JsonArray> metadataAsync(final JsonArray input) {
return Ux.future(OxField.metadata(input));
}
/**
* 元数据执行器
*
* 支持功能:
*
* - 针对字段`metadata`执行Json转换。
* - 按`visible = true/false`执行过滤,如果不存在则默认为`true`,筛选元素。
* - 针对字段`columns`执行Json转换。
*
* @param input 输入的最终响应数据
*
* @return {@link JsonArray} 同步执行结果
*/
public static JsonArray metadata(final JsonArray input) {
return OxField.metadata(input);
}
/**
* 「Node」图节点数组格式化专用方法。
*
* 格式化判断:
*
* - 如果出现相同的`globalId`则直接忽略,先执行节点合并(按`globalId`执行压缩)。
* - 每一个节点内部调用`toNode`重载方法({@link JsonObject}类型处理)。
*
* @param nodes {@link JsonArray} 待格式化的图节点数组
*
* @return {@link JsonArray} 完成格式化的图节点数组
*/
public static JsonArray toNode(final JsonArray nodes) {
return OxTo.toNode(nodes);
}
/**
* 「Node」图节点格式化专用方法。
*
* 格式化细节:
*
* - 将`globalId`赋值给`key`属性。
* - 拷贝`name`属性。
* - 拷贝`code`属性。
* - 将原始数据{@link JsonObject}拷贝到`data`属性中。
*
* @param node {@link JsonObject} 待格式化的图节点对象
*
* @return {@link JsonObject} 完成格式化的图节点
*/
public static JsonObject toNode(final JsonObject node) {
return OxTo.toNode(node);
}
/**
* 「Edge」图边数组格式化专用方法。
*
* > 内部调用`toEdge`的重载方法({@link JsonObject}类型)。
*
* @param edges {@link JsonArray} 待格式化的边数据数组
*
* @return {@link JsonArray} 已格式化的边数据数组
*/
public static JsonArray toEdge(final JsonArray edges) {
return OxTo.toEdge(edges);
}
/**
* 「Edge」图边格式化专用方法
*
* 格式化细节:
*
* - 拷贝`sourceGlobalId`到`source`属性中。
* - 拷贝`targetGlobalId`到`target`属性中。
* - 拷贝`type`边类型到`type`属性中。
* - 将原始数据{@link JsonObject}拷贝到`data`属性中。
*
* @param edge {@link JsonObject} 待格式化的边对象
*
* @return {@link JsonObject} 已格式化的边对象
*/
public static JsonObject toEdge(final JsonObject edge) {
return OxTo.toEdge(edge);
}
/**
* 提取上下游关系合并到一起。
*
* - down:下游属性。
* - up:上游属性。
*
* @param source 输入的源类型数据
* @param <T> 输入的源中元素的Java类型
*
* @return 拉平过后的关系信息
*/
public static <T> JsonArray toLinker(final T source) {
return OxTo.toLinker(source);
}
/**
* 构造比对报表
*
* @param atom {@link DataAtom}
* @param forms {@link JsonArray} 当前模型关联的表单集`UI_FORM`
* @param lists {@link JsonArray} 当前模型关联的列表集`UI_LIST`
*
* @return {@link JsonObject} 返回比对报表
*/
public static JsonArray compareUi(final DataAtom atom, final JsonArray forms, final JsonArray lists) {
return OxCompareUi.compareUi(atom, forms, lists);
}
/**
* 统一视图工具执行器
*
* `GET /api/ox/columns/:identifier/all`全列读取请求
*
* 请求数据格式
*
* - identifier:模型标识符
* - dynamic:是否动态视图(存储在`S_VIEW`中)
* - view:视图类型,默认值`DEFAULT`
*
* 除开上述参数后,还包含`Http Header`的所有信息。
*
* @param envelop
* @param identifier
*
* @return {@link Future}<{@link JsonArray}>
*/
public static Future<JsonArray> viewFull(final Envelop envelop, final String identifier) {
return OxView.viewFull(envelop, identifier);
}
/**
* 我的视图列工具执行器
*
* `GET /api/ox/columns/:identifier/my`我的视图列读取请求
*
* 请求数据格式
*
* - uri:当前请求路径
* - method:当前HTTP方法
* - 合并了所有`Http Header`的内容
*
* 返回数据格式:
*
* ```json
* // <pre><code class="json">
* {
* "user": "用户主键",
* "habitus": "构造的权限池信息",
* "view": "视图类型"
* }
* // </code></pre>
* ```
*
* @param envelop {@link Envelop} Zero标准请求模型
* @param identifier {@link String} 模型标识符
*
* @return {@link Future}<{@link JsonArray}>
*/
public static Future<JsonObject> viewMy(final Envelop envelop, final String identifier) {
return OxView.viewMy(envelop, identifier);
}
/**
* 根据<strong>应用标识</strong>和<strong>模型标识</strong>构造数据库访问器`Dao`对象。
*
* @param key {@link String} 应用标识,可以是`appId`、也可以是`sigma`
* @param identifier {@link String} 模型统一标识符
*
* @return {@link HDao} 数据库访问对象
*/
public static HDao toDao(final String key, final String identifier) {
return OxTo.toDao(key, identifier);
}
public static HDao toDao(final DataAtom atom) {
return OxTo.toDao(atom.ark().sigma(), atom.identifier());
}
/**
* 根据<strong>应用标识</strong>和<strong>模型标识</strong>构造模型定义对象。
*
* @param key {@link String} 应用标识,可以是`appId`、也可以是`sigma`
* @param identifier {@link String} 模型统一标识符
*
* @return {@link DataAtom} 模型定义
*/
public static DataAtom toAtom(final String key, final String identifier) {
return OxTo.toAtom(key, identifier);
}
/**
* 「开发专用」调试和开发专用方法(监控数据信息)。
*
* @param clazz {@link Class} 调用该函数的类
* @param <T> 函数Monad输入和输出相关数据类型
*
* @return {@link Function} 返回异步函数
*/
public static <T> Function<T[], Future<T[]>> toArray(final Class<?> clazz) {
return result -> {
LOG.Util.info(clazz, "结果数组数量:{0}", result.length);
return Ux.future(result);
};
}
/**
* 为记录主键赋值,内置调用`UUID.randomUUID().toString()`。
*
* @param data {@link JsonObject} 数据信息
* @param atom {@link DataAtom} 模型定义
*
* @return {@link JsonObject} 处理过的数据信息
*/
public static JsonObject elementUuid(final JsonObject data, final DataAtom atom) {
return OxJson.elementUuid(data, atom);
}
/**
* 「批量」为记录主键赋值,内置调用`UUID.randomUUID().toString()`。
*
* @param data {@link JsonArray} 数据信息
* @param atom {@link DataAtom} 模型定义
*
* @return {@link JsonArray} 处理过的数据信息
*/
public static JsonArray elementUuid(final JsonArray data, final DataAtom atom) {
Ut.itJArray(data).forEach(record -> elementUuid(record, atom));
return data;
}
/**
* 数组压缩,将每个元素中的`null`使用`""`替换。
*
* @param input {@link JsonArray} 待处理数组数据
* @param atom {@link DataAtom} 模型定义
*
* @return {@link JsonArray} 处理后的数据
*/
public static JsonArray elementCompress(final JsonArray input, final DataAtom atom) {
return OxJson.elementCompress(input, atom);
}
/**
* 针对插件配置的处理
*
* @param key 插件所需的Key
*
* @return
*/
public static boolean onOff(final String key) {
return OxConfig.onOff(key);
}
/**
* ## 环境静态类
*
* ### 1. 基本介绍
*
* 读取配置文件`runtime/configuration.json`构造CMDB基础环境。
*
* @author <a href="http://www.origin-x.cn">Lang</a>
*/
public interface Env {
/**
* <value>cmdb.commutator</value>,反射专用生命周期处理器配置(下层调用上层,使用反射,不能直接使用类型)。
*
* @param commutator `io.mature.extension.operation.workflow.Commutator`类型默认值
*
* @return {@link Class} 返回最终的 clazz 值
*/
static Class<?> commutator(final Class<?> commutator) {
return OxConfig.toCommutator(commutator);
}
/**
* 根据日志类型读取日志信息。
*
* @param type {@link TypeLog} 日志类型
*
* @return 返回该日志类型中的打印日志内容
*/
static String message(final TypeLog type) {
return OxConfig.toMessage(type);
}
}
public interface LOG {
String MODULE = "Προέλευση Χ";
LogModule Atom = Log.modulat(MODULE).configure("Atom");
LogModule Uca = Log.modulat(MODULE).configure("EmUca");
LogModule Hub = Log.modulat(MODULE).configure("Hub");
LogModule Shell = Log.modulat(MODULE).configure("Shell");
LogModule Plugin = Log.modulat(MODULE).configure("Infusion");
LogModule Web = Log.modulat(MODULE).configure("Web");
LogModule Util = Log.modulat(MODULE).configure("Util");
LogModule Report = Log.modulat(MODULE).configure("Report");
LogModule Status = Log.modulat(MODULE).configure("Status");
/**
* 比对报表日志器
*
* @param clazz {@link Class} 调用日志器的类
* @param compared 比对结果
*/
interface _I {
static void report(final Class<?> clazz, final ConcurrentMap<ChangeFlag, JsonArray> map) {
Report.info(clazz, "CRT", "Report Start ----- ");
map.forEach((type, data) -> Report.info(clazz, "CRT", "Type = {0}, Size = {2}, Data = {1}",
type, data.encode(), String.valueOf(data.size())));
Report.info(clazz, "CRT", "Report End ----- ");
}
}
}
}
| zero-ws/zero-entry | zero-entry-bootstrap-extension/src/main/java/io/mature/extension/refine/Ox.java |
45,418 |
import java.io.Serializable;
/*
From What's this "serialization" thing all about?:
--------------------------------------------------
It lets you take an object or group of objects, put them on a disk or send them through a wire
or wireless transport mechanism, then later, perhaps on another computer, reverse
the process: resurrect the original object(s).
The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits,
and to turn that stream of bits back into the original object(s).
Like the Transporter on Star Trek, it's all about taking something complicated and turning it
into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s
(possibly at another place, possibly at another time) and reconstructing the original
complicated "something."
So, implement the Serializable interface when you need to store a copy of the object,
send them it to another process on the same system or over the network.
Because you want to store or send an object.
It makes storing and sending objects easy. It has nothing to do with security.
*/
public abstract class Oxima implements Serializable {
private String arKykloforias;
private String montelo;
private int etosKykloforias;
private Kinitiras kinitiras;
public Oxima (String arKykloforias, String montelo, int etosKykloforias, Kinitiras kinitiras) {
this.arKykloforias = arKykloforias;
this.montelo = montelo;
this.etosKykloforias = etosKykloforias;
this.kinitiras = kinitiras;
}
public Oxima (String arKykloforias, String montelo, int etosKykloforias) {
this.arKykloforias = arKykloforias;
this.montelo = montelo;
this.etosKykloforias = etosKykloforias;
}
public String getArKykloforias() {
return arKykloforias;
}
public String toString() {
return (arKykloforias + " " + montelo + " " +etosKykloforias +
" Κινητήρας: " + kinitiras);
}
}
| kindi24/IEE-Labs | 2. Object-Oriented Programming/Ε11 - Files-Generics/E11arxeia/src/Oxima.java |
45,426 | package com.example.quickrepair.view.Technician.RegisterTechnician;
import com.example.quickrepair.dao.CustomerDAO;
import com.example.quickrepair.dao.SpecialtyDAO;
import com.example.quickrepair.dao.TechnicianDAO;
import com.example.quickrepair.domain.Customer;
import com.example.quickrepair.domain.Specialty;
import com.example.quickrepair.domain.Technician;
import com.example.quickrepair.domain.User;
import com.example.quickrepair.view.Base.BasePresenter;
import java.util.ArrayList;
public class TechnicianRegisterPresenter extends BasePresenter<TechnicianRegisterView>
{
private CustomerDAO customerDAO;
private TechnicianDAO technicianDAO;
private SpecialtyDAO specialtyDAO;
Technician technician;
/**
* Load the technician in case of edit.
*
* @param id The technician's id.
*/
public void setTechnician(int id)
{
technician = technicianDAO.find(id);
}
/**
* Try to register a technician with the given information.
*
* @param name The name of the technician.
* @param surname The surname of the technician.
* @param phoneNumber The phone number of the technician.
* @param email The email of the technician.
* @param AFM The AFM of the technician.
* @param accountNumber The bank account number of the technician.
* @param username The username of the technician.
* @param password The password of the technician.
* @param specialityID The speciality id of the technician.
*/
void registerTechnician(String name, String surname, String phoneNumber, String email, String AFM, String accountNumber, String username, String password, int specialityID, int notificationMethodID)
{
if (technician == null || technician.getUid() == 0)
{
for (Technician technician : technicianDAO.findAll())
{
if (technician.getUsername().equals(username))
{
view.showErrorMessage("Username already exist", "This username is already in use by another user.");
return;
}
else if (technician.getAFM().equals(AFM))
{
view.showErrorMessage("Duplicate AFM", "Please make sure you do not have already an account and you have typed the correct AFM.");
return;
}
}
for (Customer customer : customerDAO.findAll())
{
if (customer.getUsername().equals(username))
{
view.showErrorMessage("Username already exist", "This username is already in use by another user.");
return;
}
}
technician = new Technician();
}
try
{
technician.setTechnicianInfo(name, surname, phoneNumber, email, accountNumber, username);
technician.setPassword(password);
technician.setAFM(AFM);
}
catch (Exception e)
{
view.showErrorMessage("Invalid value", e.getMessage());
return;
}
Specialty speciality = specialtyDAO.find(specialityID);
if (speciality == null)
{
view.showErrorMessage("No speciality selected", "You must choose a speciality.");
return;
}
if (technician.getSpecialty() == null || technician.getSpecialty().getUid() != specialityID)
{
technician.setSpecialty(speciality);
}
if (notificationMethodID < 1)
{
view.showErrorMessage("No notification methods selected", "You must choose a notification method.");
return;
}
technician.setNotificationMethod(User.NotificationMethod.values()[notificationMethodID - 1]);
if (technician.getUid() == 0)
{
technician.setUid(technicianDAO.nextId());
technicianDAO.save(technician);
}
view.onSuccessfulRegister(technician.getUid());
}
/**
* Set the customer DAO for the presenter.
*
* @param customerDAO The customer DAO.
*/
void setCustomerDAO(CustomerDAO customerDAO)
{
this.customerDAO = customerDAO;
}
/**
* Set the technician DAO for the presenter.
*
* @param technicianDAO The technician DAO.
*/
void setTechnicianDAO(TechnicianDAO technicianDAO)
{
this.technicianDAO = technicianDAO;
}
/**
* Set the speciality DAO for the presenter.
*
* @param specialityDAO The speciality DAO.
*/
void setSpecialtyDAO(SpecialtyDAO specialityDAO)
{
this.specialtyDAO = specialityDAO;
}
/**
* Initialize the view.
*/
void setUpDataSource()
{
ArrayList<String> specialities = new ArrayList<>();
for (Specialty speciality : specialtyDAO.findAll())
{
specialities.add(speciality.getName().trim());
}
view.setSpecialityList(specialities, "Επιλέξτε ειδικότητα");
ArrayList<String> notificationMethods = new ArrayList<>();
for (User.NotificationMethod method : User.NotificationMethod.values())
{
notificationMethods.add(method.name().trim());
}
view.setNotificationList(notificationMethods, "Επιλέξτε τρόπο ενημέρωσης");
if (technician != null)
{
view.setName(technician.getName());
view.setSurname(technician.getSurname());
view.setEmail(technician.getEmail());
view.setPhoneNumber(technician.getPhoneNumber());
view.setAccountNumber(technician.getBankAccount());
view.setUsername(technician.getUsername());
view.setPassword(technician.getPassword());
view.setAFM(technician.getAFM());
view.setSpecialityID(technician.getSpecialty().getUid());
view.setNotificationMethodID(technician.getNotificationMethod().ordinal() + 1);
}
}
}
| NickSmyr/UndergraduateProjects | 6th semester/SoftwareEngineering/android/app/src/main/java/com/example/quickrepair/view/Technician/RegisterTechnician/TechnicianRegisterPresenter.java |
45,454 | package gr.hua.dit.smartt;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
public class NetworkTracker extends Service {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location = new Location("");// location
Location locationGPS;
Location locationWIFI;
double latitude; // latitude
double longitude; // longitude
float appAccuracy = 999;
String appProvider = "none";
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 50; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 20 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public NetworkTracker(Context context) {
this.mContext = context;
location.setLatitude(0);
location.setLongitude(0);
getLocation();
}
int intTest = 0;
// Define a listener that responds to location updates
String strProvider = "";
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location locationCurrent) {
// Called when a new location is found by the network location provider.
//makeUseOfNewLocation(location);
if (isGPSEnabled || isNetworkEnabled) {
intTest = intTest + 1;
location = locationCurrent;
appAccuracy = location.getAccuracy();
appProvider = location.getProvider();
if ((!isGPSEnabled) && appAccuracy <= 50) {
stopUsingGPS();
}
if (isGPSEnabled && appAccuracy <= 20) {
stopUsingGPS();
}
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("NETTR", String.valueOf(status));
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled || isGPSEnabled) {
this.canGetLocation = true;
}
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
//Log.d("Network", "Network");
if (locationManager != null) {
locationWIFI = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
locationGPS = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
if (locationWIFI != null) {
location = locationWIFI;
}
if (locationGPS != null) {
location = locationGPS;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
return location.getLatitude();
} else {
return 0;
}
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
return location.getLongitude();
} else {
return 0;
}
}
public String getAccuracy() {
return Float.toString(appAccuracy);
}
public String getProvider() {
return appProvider;
}
/**
* Function to check GPS/wifi enabled
*
* @return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
*/
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("Ενεργοποίηση του GPS");
// Setting Dialog Message
alertDialog.setMessage("Θέλετε να ενεργοποιήσετε το GPS;");
// On pressing Settings button
alertDialog.setPositiveButton("Ναί", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Όχι", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
} | ellak-monades-aristeias/smartt-mobile | app/src/main/java/gr/hua/dit/smartt/NetworkTracker.java |
45,488 | package gr.aueb.cf.ch6;
/**
* Δήλωση, αρχικοποίηση πίνακα και
* Populate (εισαγωγή στοιχείων)
*/
public class PopulateArray {
public static void main(String[] args) {
// Δήλωση και αρχικοποίηση πίνακα με length
int[] arr = new int[3];
arr[0] = 5;
arr[1] = 7;
arr[2] = 8;
//System.out.println(arr[0] + " " + arr[1] + " " + arr[2]);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
// Enhanced for
for (int item : arr) {
System.out.print(item + " ");
}
// Unsized Initialization
int[] arr2 = {1, 5, 8, 9, 12};
// Array Initializer
int[] arr3;
arr3 = new int[] {4, 6, 9, 10};
}
}
| a8anassis/codingfactory23a | src/gr/aueb/cf/ch6/PopulateArray.java |
45,514 | package pathfinding;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Gui extends JFrame {
/**
*
*/
private static final long serialVersionUID = -6784179367237835435L;
private Map world_;
private Point start = new Point(0,9), goal = new Point (9,0);
public static void main(String[] args) {
new Gui();
}
public Gui()
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex)
{
}
final JFrame frame = new JFrame("Grid World Pathfinding");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024, 768);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Container container = frame.getContentPane();
BorderLayout border_layout = new BorderLayout();
container.setLayout(border_layout);
world_ = new Map(10,10);
world_.setObstacle(new Point(0,0), true);
world_.setObstacle(new Point(0,3), true);
world_.setObstacle(new Point(0,4), true);
world_.setObstacle(new Point(1,0), true);
world_.setObstacle(new Point(1,3), true);
world_.setObstacle(new Point(1,4), true);
world_.setObstacle(new Point(2,3), true);
world_.setObstacle(new Point(2,4), true);
world_.setObstacle(new Point(3,7), true);
world_.setObstacle(new Point(3,8), true);
world_.setObstacle(new Point(4,7), true);
world_.setObstacle(new Point(4,8), true);
world_.setObstacle(new Point(4,2), true);
world_.setObstacle(new Point(5,8), true);
world_.setObstacle(new Point(6,4), true);
world_.setObstacle(new Point(7,4), true);
world_.setObstacle(new Point(8,4), true);
world_.setObstacle(new Point(8,3), true);
world_.setObstacle(new Point(9,4), true);
world_.setObstacle(new Point(9,3), true);
world_.setObstacle(new Point(9,8), true);
world_.setObstacle(new Point(9,9), true);
final GridPanel panel = new GridPanel(world_);
container.add(panel, BorderLayout.CENTER);
panel.start_ = start;
panel.goal_ = goal;
JPanel buttonsPanel;
buttonsPanel = new JPanel();
FlowLayout f;
f = new FlowLayout();
buttonsPanel.setLayout(f);
container.add(buttonsPanel, BorderLayout.SOUTH);
final JButton add_walls_button;
add_walls_button = new JButton("Add walls");
final JButton add_start_button;
add_start_button = new JButton("Add start");
final JButton add_goal_button;
add_goal_button = new JButton("Add goal");
add_walls_button.setEnabled(false);
add_walls_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.add_wal_ = true ;
panel.add_goal_ = false ;
panel.add_start_ = false ;
add_walls_button.setEnabled(false);
add_start_button.setEnabled(true);
add_goal_button.setEnabled(true);
}
});
buttonsPanel.add(add_walls_button);
//add_start_button.setEnabled(false);
add_start_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.add_wal_ = false ;
panel.add_goal_ = false ;
panel.add_start_ = true ;
add_walls_button.setEnabled(true);
add_start_button.setEnabled(false);
add_goal_button.setEnabled(true);
}
});
buttonsPanel.add(add_start_button);
//add_goal_button.setEnabled(false);
add_goal_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.add_wal_ = false ;
panel.add_goal_ = true ;
panel.add_start_ = false ;
add_walls_button.setEnabled(true);
add_start_button.setEnabled(true);
add_goal_button.setEnabled(false);
}
});
buttonsPanel.add(add_goal_button);
JButton btnResetWorld = new JButton("Reset World");
btnResetWorld.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e)
{
try
{
int w = Integer.valueOf(JOptionPane.showInputDialog("What is the world's width?"));
int h = Integer.valueOf(JOptionPane.showInputDialog("What is the world's height?"));
if (w > 0 && h >0 )
{
world_ = new Map(h,w);
panel.resetWorld(world_);
panel.repaint();
}
else
{
//TODO Να μπει μνμ προειδοποίησης
}
}
catch(NumberFormatException e_num)
{
}
}
});
buttonsPanel.add(btnResetWorld);
JButton btnAstar = new JButton("ASTAR");
btnAstar.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (panel.start_ != null && panel.goal_ !=null)
{
AStar astar = new AStar(panel.start_,panel.goal_, world_);
//System.out.println ("Starting A Star");
//System.out.println("World:\n " + world_.toString());
LinkedList<Node> path = astar.findPath();
if (path == null)
{
//System.out.println("empty");
JOptionPane.showMessageDialog(frame,
"No path was found.",
"Message",
JOptionPane.INFORMATION_MESSAGE);
}
else
{
panel.drawPath(path);
//System.out.println("Path: " + path.toString());
}
}
else
{
JOptionPane.showMessageDialog(frame,
"Please place the start and the goal squares.",
"Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
buttonsPanel.add(btnAstar);
JButton btnPso = new JButton("PSO");
btnPso.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (panel.start_ != null && panel.goal_ !=null)
{
PSO pso = new PSO(panel.start_,panel.goal_, world_, 100);
//System.out.println ("Starting A Star");
//System.out.println("World:\n " + world_.toString());
LinkedList<Node> path = pso.findPath();
if (path == null)
{
//System.out.println("empty");
JOptionPane.showMessageDialog(frame,
"No path was found.",
"Message",
JOptionPane.INFORMATION_MESSAGE);
}
else
{
panel.drawPath(path);
//System.out.println("Path: " + path.toString());
}
}
else
{
JOptionPane.showMessageDialog(frame,
"Please place the start and the goal squares.",
"Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
buttonsPanel.add(btnPso);
}
});
}
//http://stackoverflow.com/questions/15421708/how-to-draw-grid-using-swing-class-java-and-detect-mouse-position-when-click-and
public class GridPanel extends JPanel
{
/**
*
*/
private static final long serialVersionUID = -4261360122735571252L;
private int column_count_;
private int row_count_;
private List<Rectangle> cells_ = new ArrayList<Rectangle>();
private Map world_;
private Point selected_cell;
private LinkedList<Node> path_;
// Variabels for setting the start point and the goal point
public boolean add_wal_ = true;
public boolean add_start_ = false;
public boolean add_goal_ = false;
public Point start_ , goal_ ;
public GridPanel(Map world )
{
column_count_= world.getHeight();
row_count_=world.getWidth();
world_ = world;
MouseAdapter mouseHandler;
mouseHandler = new MouseAdapter()
{
@Override
public void mouseMoved(MouseEvent e)
{
int width = getWidth();
int height = getHeight();
int cellWidth = width / column_count_;
int cellHeight = height / row_count_;
int column = e.getX() / cellWidth;
int row = e.getY() / cellHeight;
selected_cell = new Point(column, row);
repaint();
}
@Override
public void mouseClicked(MouseEvent e)
{
int width = getWidth();
int height = getHeight();
int cellWidth = width / column_count_;
int cellHeight = height / row_count_;
int column = e.getX() / cellWidth;
int row = e.getY() / cellHeight;
selected_cell = new Point(column, row);
if (add_wal_)
{
if (!world_.getNode(selected_cell).isObstacle())
{
world_.setObstacle(selected_cell, true);
}
else
{
world_.setObstacle(selected_cell, false);
}
}
else if (add_start_)
{
start_ = selected_cell;
}
else if (add_goal_)
{
goal_ = selected_cell;
}
repaint();
}
};
addMouseMotionListener(mouseHandler);
addMouseListener(mouseHandler);
}
public void resetWorld(Map world)
{
goal_ = null;
start_ = null;
column_count_= world.getHeight();
row_count_=world.getWidth();
world_ = world;
resetWorld();
}
public void resetWorld()
{
try
{
cells_.clear();
path_.clear();
}
catch(NullPointerException e)
{
}
}
@Override
public Dimension getPreferredSize()
{
return new Dimension(200, 200);
}
@Override
public void invalidate()
{
cells_.clear();
selected_cell = null;
super.invalidate();
}
protected void drawPath( LinkedList<Node> path )
{
path_ = path;
repaint();
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int width = getWidth();
int height = getHeight();
int cellWidth = width / column_count_;
int cellHeight = height / row_count_;
int xOffset = (width - (column_count_ * cellWidth)) / 2;
int yOffset = (height - (row_count_ * cellHeight)) / 2;
if (cells_.isEmpty())
{
for (int row = 0; row < row_count_; row++)
{
for (int col = 0; col < column_count_; col++)
{
Rectangle cell = new Rectangle(
xOffset + (col * cellWidth),
yOffset + (row * cellHeight),
cellWidth,
cellHeight);
cells_.add(cell);
}
}
}
for (int row = 0; row < row_count_; row++)
{
for (int col = 0; col < column_count_; col++)
{
Rectangle cell = cells_.get(row * column_count_ + col);
if (world_.getNode(new Point(col,row)).isObstacle())
{
g2d.setColor(Color.GRAY);
g2d.fill(cell);
}
else
{
g2d.setColor(Color.WHITE);
g2d.fill(cell);
}
}
}
if (selected_cell != null)
{
try
{
int index = selected_cell.x + (selected_cell.y * column_count_);
Rectangle cell = cells_.get(index);
g2d.setColor(Color.BLUE);
g2d.fill(cell);
}
catch(IndexOutOfBoundsException e)
{
//do nothing
}
}
g2d.setColor(Color.GRAY);
for (Rectangle cell : cells_)
{
g2d.draw(cell);
}
//draw start point
if (start_ != null)
{
Rectangle cell = cells_.get((int) (start_.getY() * column_count_ + start_.getX()));
g2d.setColor(Color.GREEN);
g2d.fill(cell);
}
//draw goal point
if (goal_ != null)
{
Rectangle cell = cells_.get((int) (goal_.getY() * column_count_ + goal_.getX()));
g2d.setColor(Color.RED);
g2d.fill(cell);
}
// draw path
if (path_ != null)
{
g2d.setColor(Color.BLUE);
for (int idx=0, size = path_.size(); idx < size; ++idx)
{
g2d.fillOval(
path_.get(idx).getPosition().x * cellWidth,
path_.get(idx).getPosition().y * cellHeight,
cellWidth,
cellHeight);
}
}
g2d.dispose();
}
}
}
| giokats/PathFinding | src/pathfinding/Gui.java |
45,553 | /*
* DB
*
* Copyright 2024 Bugs Bunny
*/
package gr.aueb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Manages database connections for the "bugsbunny" database.
*
* The class provides methods to establish and close connections to the database
* server.
* It utilizes the MySQL JDBC driver to interact with the database.
* The connection settings, including the database name, server address,
* username, and password,
* are defined as constants.
*
* @version 1.8 released on 15th January 2024
* @author Μαρκέλλα Χάσικου και Άγγελος Λαγός
*/
public class DB implements AutoCloseable {
// Database connection settings, change dbName, dbUsername, dbPassword
/** The address of the database server. */
private final String dbServer = "localhost";
/** The port number for the database server. */
private final String dbServerPort = "3306";
/** The name of the database. */
private final String dbName = "bugsbunny";
/** The username for connecting to the database. */
private final String dbUsername = "root";
/** The password for connecting to the database. */
private final String dbPassword = ""; //Your password
/** The database connection object. */
private Connection con = null;
/**
* Establishes a connection with the database.
*
* @return The initialized database connection.
* @throws Exception if there is an error during the connection process.
*/
public Connection getConnection() throws Exception {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
throw new Exception("MySQL Driver error: " + e.getMessage());
}
try {
con = DriverManager.getConnection("jdbc:mysql://"
+ dbServer + ":" + dbServerPort + "/" + dbName, dbUsername, dbPassword);
return con;
} catch (Exception e) {
// throw Exception if any error occurs
throw new Exception("Could not establish connection with the Database Server: "
+ e.getMessage());
}
} // End of getConnection
/**
* Closes the database connection.
*
* @throws SQLException if there is an error during the closing process.
*/
public void close() throws SQLException {
try {
if (con != null)
con.close(); // close the connection to the database to end the database session
} catch (SQLException e) {
throw new SQLException("Could not close connection with the Database Server: "
+ e.getMessage());
}
}
}
| Aglag257/Java2_AIApp | app/src/main/java/gr/aueb/DB.java |
45,557 | package makisp.gohome;
/**
* Created by Ευάγγελος Πετρόπουλος on 3/11/2016.
*/
public class Credential {
private int id;
private String username;
private String password;
private int progress;
///// Άδειος κατασκευάστης /////
public Credential(){
}
///// Κατασκευάστης /////
public Credential(int id, String username, String password, int progress){
this.id = id;
this.username = username;
this.password = password;
this.progress = progress;
}
///// Κατασκευάστης /////
public Credential(String username, String password, int progress){
this.username = username;
this.password = password;
this.progress = progress;
}
public void setId(int id){
this.id = id;
}
public void setUsername(String username){
this.username = username;
}
public void setPassword(String password){
this.password = password;
}
public void setProgress(int progress){
this.progress= progress;
}
public int getId(){
return id;
}
public String getUsername(){
return username;
}
public String getPassword(){
return password;
}
public int getProgress(){
return progress;
}
}
| teicm-project/go-home | app/src/main/java/makisp/gohome/Credential.java |
45,559 | /*
* Message
*
* Copyright 2024 Bugs Bunny
*/
package gr.aueb;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Represents messages in a chatroom, stored in a database.
*
* The class includes methods for updating message details, adding messages to
* the database,
* and deleting messages. It also provides methods to fetch and set message
* attributes such as
* spoiler status and text. The class interacts with the database using JDBC.
*
* @version 1.8 released on 15th January 2024
* @author Μαρκέλλα Χάσικου και Άγγελος Λαγός
*/
public class Message {
/** The unique identifier for the message. */
private final int messageId;
/** The user ID associated with the message. */
private final int userId;
/** The spoiler status of the message. */
private boolean spoiler;
/** The text content of the message. */
private String text;
/** The chatroom ID associated with the message. */
private final int chatroomId;
/** The username of the user who sent the message. */
private String username;
/** Constructs a Message object with specified attributes. */
public Message(int messageId, int userId, boolean spoiler, String text, int chatroomId, String username) {
this.messageId = messageId;
this.userId = userId;
this.spoiler = spoiler;
this.text = text;
this.chatroomId = chatroomId;
this.username = username;
}
/**
* Gets the unique identifier for the message.
*
* @return The message ID.
*/
public int getMessageId() {
return messageId;
}
/**
* Gets the user ID associated with the message.
*
* @return The user ID.
*/
public int getUserId() {
return userId;
}
/**
* Gets the spoiler status of the message.
*
* @return The spoiler status.
*/
public boolean getSpoiler() {
return spoiler;
}
/**
* Sets the spoiler status of the message and updates it in the database.
*
* @param spoiler The new spoiler status.
* @throws Exception if there is an error during the update process.
*/
public void setSpoiler(boolean spoiler) throws Exception {
this.spoiler = spoiler;
updateSpoilerInDatabase();
}
/**
* Updates the spoiler status of the message in the database.
*
* @throws Exception if there is an error during the update process.
*/
private void updateSpoilerInDatabase() throws Exception {
DB db = new DB();
Connection con = null;
PreparedStatement stmt = null;
try {
con = db.getConnection();
stmt = con.prepareStatement("UPDATE message SET spoiler=? WHERE id=?");
stmt.setBoolean(1, spoiler);
stmt.setInt(2, messageId);
stmt.executeUpdate();
System.out.println("Spoiler updated in the database");
} catch (Exception e) {
throw new Exception(e.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
if (db != null) {
db.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Gets the text content of the message.
*
* @return The message text.
*/
public String getText() {
return text;
}
/**
* Sets the text content of the message and updates it in the database.
*
* @param text The new message text.
* @throws Exception if there is an error during the update process.
*/
public void setText(String text) throws Exception {
this.text = text;
updateTextInDatabase();
}
/**
* Updates the text content of the message in the database.
*
* @throws Exception if there is an error during the update process.
*/
private void updateTextInDatabase() throws Exception {
DB db = null;
Connection con = null;
PreparedStatement stmt = null;
try {
db = new DB();
con = db.getConnection();
stmt = con.prepareStatement("UPDATE message SET text=? WHERE id=?");
stmt.setString(1, text);
stmt.setInt(2, messageId);
stmt.executeUpdate();
System.out.println("Text updated in the database");
} catch (Exception e) {
throw new Exception(e.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
if (db != null) {
db.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Gets the chatroom ID associated with the message.
*
* @return The chatroom ID.
*/
public int getChatroomId() {
return chatroomId;
}
/**
* Gets the username of the user who sent the message.
*
* @return The username.
*/
public String getUsername() {
return username;
}
/**
* Adds a new message to the database and returns a corresponding Message
* object.
*
* @param userId The user ID associated with the message.
* @param spoiler The spoiler status of the message.
* @param text The text content of the message.
* @param chatroomId The chatroom ID associated with the message.
* @param username The username of the user who sent the message.
* @return The newly created Message object.
* @throws Exception if there is an error during the insertion process.
*/
public static Message addMessage(int userId, boolean spoiler, String text, int chatroomId, String username)
throws Exception {
try (
DB db = new DB();
Connection con = db.getConnection();
PreparedStatement stmt = con.prepareStatement(
"INSERT INTO Message (userId, spoiler, text, roomId, username) VALUES (?, ?, ?, ?, ?)",
Statement.RETURN_GENERATED_KEYS);) {
stmt.setInt(1, userId);
stmt.setBoolean(2, spoiler);
stmt.setString(3, text);
stmt.setInt(4, chatroomId);
stmt.setString(5, username);
int affectedRows = stmt.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating message failed, no rows affected.");
}
// Get the generated messageId
try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
if (generatedKeys.next()) {
int messageId = generatedKeys.getInt(1);
// Insert into UnSeenMessage for all other members of the chatroom
insertIntoUnSeenMessage(chatroomId, userId, messageId);
// Return a new Message object with the generated messageId and other fields
return new Message(messageId, userId, spoiler, text, chatroomId, username);
} else {
throw new SQLException("Creating message failed, no ID obtained.");
}
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* Helper method to insert into UnSeenMessage for all other members of the
* chatroom.
*
* @param chatroomId The chatroom ID.
* @param senderUserId The user ID of the message sender.
* @param messageId The ID of the newly created message.
* @throws Exception if there is an error during the insertion process.
*/
private static void insertIntoUnSeenMessage(int chatroomId, int senderUserId, int messageId) throws Exception {
try (
DB db = new DB();
Connection con = db.getConnection();
PreparedStatement stmt = con.prepareStatement(
"INSERT INTO UnSeenMessage (userId, roomId, UnSeenMessageId) SELECT userId, ?, ? FROM ChatroomUser WHERE roomId = ? AND userId <> ?");) {
stmt.setInt(1, chatroomId);
stmt.setInt(2, messageId);
stmt.setInt(3, chatroomId);
stmt.setInt(4, senderUserId);
stmt.executeUpdate();
} catch (Exception e) {
throw new Exception("Error inserting into UnSeenMessage: " + e.getMessage());
}
}
/**
* Deletes a message from the database.
*
* @param userId The user ID attempting to delete the message.
* @throws Exception if the user does not have permission or if there is an
* error during the deletion process.
*/
public void deleteMessage(int userId) throws Exception {
if (this.getUserId() != userId) {
throw new Exception("User does not have permission to delete this message.");
}
int messageId = this.getMessageId();
int chatroomId = this.getChatroomId();
try (
DB db = new DB();
Connection con = db.getConnection();
PreparedStatement stmtDeleteMessage = con.prepareStatement("DELETE FROM Message WHERE id = ?");
PreparedStatement stmtDeleteUnSeenMessage = con
.prepareStatement("DELETE FROM UnSeenMessage WHERE UnSeenMessageId = ?");) {
// Delete from Message table
stmtDeleteMessage.setInt(1, messageId);
stmtDeleteMessage.executeUpdate();
// Delete from UnSeenMessage table
stmtDeleteUnSeenMessage.setInt(1, messageId);
stmtDeleteUnSeenMessage.executeUpdate();
System.out.println("\nMessage deleted successfully!");
} catch (Exception e) {
throw new Exception("Error deleting message: " + e.getMessage());
}
}
/**
* Returns a string representation of the Message object.
*
* @return A string representation including message details.
*/
@Override
public String toString() {
String spoilerStatus = spoiler ? "Yes" : "No";
return String.format("Author: %s\nSpoiler: %s\n%s", username, spoilerStatus, text);
}
} | Aglag257/Java2_AIApp | app/src/main/java/gr/aueb/Message.java |
45,563 | package makisp.gohome;
import android.test.AndroidTestCase;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
/**
* Created by Ευάγγελος Πετρόπουλος on 4/12/2016.
*/
///// Instrumented Tests /////
public class DbCredentialsTest extends AndroidTestCase {
private DbCredentials dbCredentials;
private Credential credential;
private List<Credential> credentialList;
@Before
public void setUp(){
dbCredentials = new DbCredentials(mContext);
}
@After
public void finish(){
dbCredentials.close();
mContext.deleteDatabase(DbCredentials.DATABASE_NAME);
}
@Test
public void testAddGetCredentialIsNotNull() throws Exception{
dbCredentials.addCredential(new Credential(1, "Ευάγγελος", "123456789", 1));
credential = dbCredentials.getCredential(1);
assertNotNull(credential);
}
@Test
public void testAddGetCredentialExpectedValues() throws Exception{
int actualId, actualProgress;
String actualUsername, actualPassword;
dbCredentials.addCredential(new Credential(1, "Ευάγγελος", "123456789", 1));
credential = dbCredentials.getCredential(1);
actualId = credential.getId();
actualUsername = credential.getUsername();
actualPassword = credential.getPassword();
actualProgress = credential.getProgress();
assertEquals(1, actualId);
assertEquals("Ευάγγελος", actualUsername);
assertEquals("123456789", actualPassword);
assertEquals(1, actualProgress);
}
@Test
public void testGetAllCredentialsIsNotNull() throws Exception{
dbCredentials.addCredential(new Credential(1, "Ευάγγελος", "123456789", 1));
credentialList = dbCredentials.getAllCredentials();
assertNotNull(credentialList);
}
@Test
public void testGetAllCredentialsIsInList() throws Exception{
int actualId = 0, actualProgress = 0;
String actualUsername = "", actualPassword = "";
dbCredentials.addCredential(new Credential(1, "Ευάγγελος", "123456789", 1));
credentialList = dbCredentials.getAllCredentials();
for(Credential credential : credentialList) {
actualId = credential.getId();
actualUsername = credential.getUsername();
actualPassword = credential.getPassword();
actualProgress = credential.getProgress();
break;
}
assertEquals(1, actualId);
assertEquals("Ευάγγελος", actualUsername);
assertEquals("123456789", actualPassword);
assertEquals(1, actualProgress);
}
@Test
public void testGetCredentialsCountIsNotNull() throws Exception{
int count;
count = dbCredentials.getCredentialsCount();
assertNotNull(count);
}
@Test
public void testGetCredentialsCountIs1() throws Exception{
int count;
count = dbCredentials.getCredentialsCount();
assertEquals(1,count);
}
@Test
public void testUpdateCredential1RowUpdated() throws Exception{
int update;
credential = new Credential(1, "Βαγγέλης", "987654321", 10);
update = dbCredentials.updateCredential(credential);
assertEquals(1,update);
}
@Test
public void testUpdateCredential1RowUpdatedExpectedActual() throws Exception{
Credential updatedCredential = dbCredentials.getCredential(1);
assertEquals(1, updatedCredential.getId());
assertEquals("Βαγγέλης", updatedCredential.getUsername());
assertEquals("987654321", updatedCredential.getPassword());
assertEquals(10, updatedCredential.getProgress());
}
@Test
public void testUpdateCredentialExpectedActual() throws Exception{
Credential credentialUpdate = new Credential(1, "Ευάγγελος", "123456789", 1);
dbCredentials.updateCredential(credentialUpdate);
Credential actualCredential = dbCredentials.getCredential(1);
assertEquals(1, actualCredential.getId());
assertEquals("Ευάγγελος", actualCredential.getUsername());
assertEquals("123456789", actualCredential.getPassword());
assertEquals(1, actualCredential.getProgress());
}
@Test
public void testDeleteCredentialWithId1IsNull() throws Exception{
Credential credentialToDelete = new Credential(1, "Ευάγγελος", "123456789", 1);
dbCredentials.deleteCredential(credentialToDelete);
credential = dbCredentials.getCredential(1);
assertNull(credential);
}
@Test
public void testAddGetItemIsNotNull() throws Exception{
Inventory inventory;
dbCredentials.addItem(new Inventory(1, "Φτιάρι"));
inventory = dbCredentials.getItem(1);
assertNotNull(inventory);
}
@Test
public void testAddGetItemIsNull() throws Exception{
Inventory inventory;
dbCredentials.addItem(new Inventory(1, "Φτιάρι"));
inventory = dbCredentials.getItem(0);
assertNull(inventory);
}
@Test
public void testAddGetItemExpectedValues() throws Exception{
Inventory inventory;
int actualId;
String actualItem;
dbCredentials.addItem(new Inventory(1, "Φτιάρι"));
inventory = dbCredentials.getItem(1);
actualId = inventory.getId();
actualItem = inventory.getItem();
assertEquals(1, actualId);
assertEquals("Φτιάρι", actualItem);
}
@Test
public void testGetAllItemsIsNotNull() throws Exception{
List<Inventory> itemsList;
dbCredentials.addItem(new Inventory(1, "Φτιάρι"));
itemsList = dbCredentials.getAllItems();
assertNotNull(itemsList);
}
@Test
public void testGetAllItemsIsInList() throws Exception{
List<Inventory> itemsList;
int actualId = 0;
String actualItem = "";
dbCredentials.addItem(new Inventory(1, "Φτιάρι"));
itemsList = dbCredentials.getAllItems();
for(Inventory items : itemsList) {
actualId = items.getId();
actualItem = items.getItem();
break;
}
assertEquals(1, actualId);
assertEquals("Φτιάρι", actualItem);
}
@Test
public void testGetItemsCountIsNotNull() throws Exception{
int count;
count = dbCredentials.getItemsCount(1);
assertNotNull(count);
}
@Test
public void testGetItemsOfActiveUserCountIsGreaterThan1() throws Exception{
int count;
boolean greater = false;
count = dbCredentials.getItemsCount(1);
if(count > 0)
greater = true;
assertTrue(greater);
}
@Test
public void testGetItemsOfActiveUserCountIsLessThan1() throws Exception{
int count;
boolean greater = true;
count = dbCredentials.getItemsCount(2);
if(!(count > 0))
greater = false;
assertFalse(greater);
}
@Test
public void testUpdateItemRowsUpdated() throws Exception{
Inventory inventory;
int update;
boolean updated = false;
inventory = new Inventory(1, "Μαχαίρι");
update = dbCredentials.updateItem(inventory);
if(update > 0)
updated = true;
assertTrue(updated);
}
@Test
public void testUpdateItem1RowsUpdatedExpectedActual() throws Exception{
Inventory updatedItem = dbCredentials.getItem(1);
assertEquals(1, updatedItem.getId());
assertEquals("Φτιάρι", updatedItem.getItem());
}
@Test
public void testUpdateItemsExpectedActual() throws Exception{
Inventory inventoryUpdate = new Inventory(1, "Φτιάρι");
dbCredentials.updateItem(inventoryUpdate);
Inventory actualItem = dbCredentials.getItem(1);
assertEquals(1, actualItem.getId());
assertEquals("Φτιάρι", actualItem.getItem());
}
@Test
public void testDeleteItemWithId1IsNull() throws Exception{
Inventory itemToDelete = new Inventory(1, "Φτιάρι");
dbCredentials.deleteItem(itemToDelete);
Inventory item = dbCredentials.getItem(1);
assertNull(item);
}
@Test
public void testAddMarkerIsNotNull(){
Markers markers = new Markers();
markers.setId(1);
markers.setLatitude(59856.5);
markers.setLongitude(48595.5);
dbCredentials.addMarkers(markers);
Assert.assertNotNull(dbCredentials.getMarker(1));
}
@Test
public void testGetMarkerExpected(){
Markers expectedMarker = new Markers();
expectedMarker.setId(1);
expectedMarker.setLatitude(59856.5);
expectedMarker.setLongitude(48595.5);
dbCredentials.addMarkers(expectedMarker);
Markers actualMarker = dbCredentials.getMarker(1);
Assert.assertNotNull(actualMarker);
Assert.assertEquals(expectedMarker.getId(), actualMarker.getId());
Assert.assertEquals(expectedMarker.getLatitude(), actualMarker.getLatitude(), expectedMarker.getLatitude()-actualMarker.getLatitude());
Assert.assertEquals(expectedMarker.getLongitude(), actualMarker.getLongitude(), expectedMarker.getLongitude()-actualMarker.getLongitude());
}
@Test
public void testGetAllMarkersIsNotNull(){
dbCredentials.addMarkers(new Markers(2, 568.5, 598.4));
List<Markers> markersList = dbCredentials.getAllMarkers();
assertNotNull(markersList);
}
@Test
public void testGetAllMarkersIsInList() throws Exception{
int actualId = 0;
double actualLatitude=0, actualLongitude=0;
dbCredentials.addMarkers(new Markers(3, 568.5, 598.4));
List<Markers> markersList = dbCredentials.getAllMarkers();
for(Markers markers : markersList) {
actualId = markers.getId();
actualLatitude = markers.getLatitude();
actualLongitude = markers.getLongitude();
break;
}
assertEquals(1, actualId);
assertEquals(59856.5, actualLatitude);
assertEquals(48595.5, actualLongitude);
}
@Test
public void testGetMarkersCountIsNotNull() throws Exception{
int count;
count = dbCredentials.getMarkersCount();
assertNotNull(count);
}
@Test
public void testGetMarkersCountIs3() throws Exception{
int count;
count = dbCredentials.getMarkersCount();
assertEquals(3,count);
}
@Test
public void testUpdateMarker1RowUpdated() throws Exception{
int update;
Markers marker = new Markers(1, 56.5, 89.5);
update = dbCredentials.updateMarkers(marker);
assertEquals(1,update);
}
@Test
public void testUpdateMarker1RowUpdatedExpectedActual() throws Exception{
Markers updatedMarker = dbCredentials.getMarker(1);
assertEquals(1, updatedMarker.getId());
assertEquals(56.5, updatedMarker.getLatitude());
assertEquals(89.5, updatedMarker.getLongitude());
}
/**
* Created by Iwanna Pantoyla on 6/12/2016.
*/
@Test
public void testDeleteMarkers() throws Exception{
Markers deleteMarker = new Markers(1,1);
dbCredentials.deleteMarkers(deleteMarker);
Markers marker = dbCredentials.getMarker(1);
assertNull(marker);
}
}
| teicm-project/go-home | app/src/androidTest/java/makisp/gohome/DbCredentialsTest.java |
45,568 | /*
* MovieDAO
*
* Copyright 2024 Bugs Bunny
*/
package gr.aueb;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
* Data Access Object (DAO) for Movie-related database operations.
*
* The class facilitates interactions with the database concerning movies,
* particularly focusing on reviews. It handles standard database queries and
* transactions
* associated with movies and their reviews.
* Key operations provided include fetching reviews for a specific movie,
* retrieving
* spoiler-free reviews, and calculating the average rating for a movie.
*
* @version 1.8 released on 15th January 2024
* @author Άγγελος Λαγός
*/
public class MovieDAO {
/**
* Retrieves all reviews for a specific movie ID from the database.
*
* @param movieId The ID of the movie.
* @return A list of reviews for the specified movie.
* @throws Exception If an error occurs during database interaction.
*/
public static ArrayList<Review> getAllReviewsForMovie(int movieId) throws Exception {
ArrayList<Review> reviews = new ArrayList<>();
try (DB db = new DB();
Connection con = db.getConnection();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM Review WHERE movieId = ?")) {
stmt.setInt(1, movieId);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int reviewId = rs.getInt("reviewId");
int userId = rs.getInt("userId");
String reviewText = rs.getString("review_text");
float rating = rs.getFloat("rating");
boolean spoiler = rs.getBoolean("spoiler");
String username = rs.getString("username");
java.sql.Date date = rs.getDate("date");
String movieName = rs.getString("movieName");
Review review = new Review(reviewId, userId, movieId, reviewText, rating, spoiler, username,
new java.util.Date(date.getTime()), movieName);
reviews.add(review);
}
}
}
return reviews;
}
/**
* Retrieves spoiler-free reviews for a specific movie ID from the database.
*
* @param movieId The ID of the movie.
* @return A list of spoiler-free reviews for the specified movie.
* @throws Exception If an error occurs during database interaction.
*/
public static ArrayList<Review> getSpoilerFreeReviewsForMovie(int movieId) throws Exception {
ArrayList<Review> spoilerFreeReviews = new ArrayList<>();
try (DB db = new DB();
Connection con = db.getConnection();
PreparedStatement stmt = con
.prepareStatement("SELECT * FROM Review WHERE movieId = ? AND spoiler = false")) {
stmt.setInt(1, movieId);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int reviewId = rs.getInt("reviewId");
int userId = rs.getInt("userId");
String reviewText = rs.getString("review_text");
float rating = rs.getFloat("rating");
boolean spoiler = rs.getBoolean("spoiler");
String username = rs.getString("username");
java.sql.Date date = rs.getDate("date");
String movieName = rs.getString("movieName");
Review review = new Review(reviewId, userId, movieId, reviewText, rating, spoiler, username,
new java.util.Date(date.getTime()), movieName);
spoilerFreeReviews.add(review);
}
}
}
return spoilerFreeReviews;
}
/**
* Calculates the average rating for a specific movie ID based on reviews in the
* database.
*
* @param movieId The ID of the movie.
* @return The average rating for the specified movie.
* @throws Exception If an error occurs during database interaction.
*/
public static double getAverageRatingForMovie(int movieId) throws Exception {
double averageRating = 0;
int totalReviews = 0;
double totalRating = 0;
try (DB db = new DB();
Connection con = db.getConnection();
PreparedStatement stmt = con.prepareStatement("SELECT rating FROM Review WHERE movieId = ?")) {
stmt.setInt(1, movieId);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
float rating = rs.getFloat("rating");
totalRating += rating;
totalReviews++;
}
}
if (totalReviews > 0) {
averageRating = totalRating / totalReviews;
BigDecimal bd = new BigDecimal(averageRating).setScale(2, RoundingMode.HALF_UP);
averageRating = bd.doubleValue();
}
}
return averageRating;
}
}
| Aglag257/Java2_AIApp | app/src/main/java/gr/aueb/MovieDAO.java |
45,569 | /*
* Chatroom
*
* Copyright 2024 Bugs Bunny
*/
package gr.aueb;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
/**
* Represents a chatroom in the application.
* This class provides methods to manage and interact with chatrooms,
* including creating, updating, and retrieving information about chatrooms.
*
* @version 1.8 28 January 2024
* @author Άγγελος Λαγός και Μαρκέλλα Χάσικου
*
*/
public class Chatroom {
/** Unique identifier for the chatroom. */
private final int roomId;
/** Name of the chatroom. */
private String name;
/** Creator's user ID. */
private final int creatorId;
/**
* Constructs a new Chatroom instance with the specified parameters.
*
* @param roomId Unique identifier for the chatroom.
* @param name Name of the chatroom.
* @param userId Creator's user ID.
*/
public Chatroom(int roomId, String name, int userId) {
this.roomId = roomId;
this.name = name;
this.creatorId = userId;
}
/**
* Gets the unique identifier of the chatroom.
*
* @return The unique identifier of the chatroom.
*/
public int getRoomId() {
return roomId;
}
/**
* Gets the name of the chatroom.
*
* @return The name of the chatroom.
*/
public String getName() {
return name;
}
/**
* Gets the creator's user ID.
*
* @return The creator's user ID.
*/
public int getCreatorId() {
return creatorId;
}
/**
* Sets the name of the chatroom if the calling user is the creator.
*
* @param name The new name for the chatroom.
* @param userId The user ID making the update request.
* @throws Exception If the user is not the creator, the update is not allowed.
*/
public void setName(String name, int userId) throws Exception {
if (!isChatroomCreator(userId)) {
// If the user is not the creator, do not allow the update
System.out.println("Only the creator can update the chatroom name.");
return;
}
this.name = name;
updateNameInDatabase();
}
/**
* Checks if the specified user is the creator of the chatroom.
*
* @param userId The user ID to check.
* @return True if the user is the creator; otherwise, false.
*/
public boolean isChatroomCreator(int userId) {
DB db = new DB();
try (Connection con = db.getConnection();
PreparedStatement stmt = con
.prepareStatement("SELECT COUNT(*) FROM Chatroom WHERE roomId = ? AND creatorId = ?")) {
stmt.setInt(1, roomId);
stmt.setInt(2, userId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return rs.getInt(1) > 0;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
/**
* Updates the chatroom name in the database.
*
* @throws Exception If there is an issue updating the name in the database
* or if a chatroom with the new name already exists.
*/
private void updateNameInDatabase() throws Exception {
if (isNameUnique(name)) {
DB db = new DB();
try (Connection con = db.getConnection();
PreparedStatement stmt = con.prepareStatement("UPDATE Chatroom SET name = ? WHERE roomId = ?")) {
stmt.setString(1, name);
stmt.setInt(2, roomId);
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Failed to update name in the database.");
} finally {
try {
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
throw new Exception("Chatroom with the same name already exists. Choose a different name.");
}
}
/**
* Checks if a chatroom with the given name already exists.
*
* @param newName The name to check for uniqueness.
* @return True if the name is unique; otherwise, false.
*/
public static boolean isNameUnique(String newName) {
DB db = new DB();
try (Connection con = db.getConnection();
PreparedStatement stmt = con.prepareStatement("SELECT COUNT(*) FROM Chatroom WHERE name = ?")) {
stmt.setString(1, newName);
try (ResultSet rs = stmt.executeQuery()) {
rs.next();
return rs.getInt(1) == 0; // If count is 0, the name is unique
}
} catch (Exception e) {
e.printStackTrace();
return false; // Handle the exception or log it accordingly
} finally {
try {
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Creates a new chatroom and adds it to the database.
*
* @param name The name of the new chatroom.
* @param creatorId The user ID of the creator.
* @return The newly created Chatroom instance.
* @throws Exception If there is an issue creating the chatroom.
*/
public static Chatroom createChatroom(String name, int creatorId) throws Exception {
try (DB db = new DB(); Connection con = db.getConnection()) {
int roomId;
String sql1 = "INSERT INTO Chatroom(name, creatorId) VALUES(?, ?);";
String sql2 = "INSERT INTO ChatroomUser VALUES(?,?)";
try (PreparedStatement stmt1 = con.prepareStatement(sql1, Statement.RETURN_GENERATED_KEYS)) {
stmt1.setString(1, name);
stmt1.setInt(2, creatorId);
stmt1.executeUpdate();
try (ResultSet generatedId = stmt1.getGeneratedKeys()) {
if (generatedId.next()) {
roomId = generatedId.getInt(1);
} else {
throw new Exception("Failed to retrieve generated roomId.");
}
}
}
try (PreparedStatement stmt2 = con.prepareStatement(sql2)) {
stmt2.setInt(1, roomId);
stmt2.setInt(2, creatorId);
stmt2.executeUpdate();
System.out.println("\nChatroom " + name + " created successfully!");
}
return new Chatroom(roomId, name, creatorId);
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* Retrieves a list of all chatrooms from the database.
*
* @return An ArrayList containing all chatrooms.
* @throws Exception If there is an issue retrieving chatrooms from the
* database.
*/
public static ArrayList<Chatroom> getChatrooms() throws Exception {
ArrayList<Chatroom> chatrooms = new ArrayList<>();
DB db = new DB();
Connection con = null;
try {
con = db.getConnection();
try (PreparedStatement stmt = con.prepareStatement("SELECT * from chatroom;");
ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int roomId = rs.getInt("roomId");
String name = rs.getString("name");
int creatorId = rs.getInt("creatorId");
Chatroom chatroom = new Chatroom(roomId, name, creatorId);
chatrooms.add(chatroom);
}
}
} catch (Exception e) {
throw new Exception(e.getMessage());
} finally {
try {
if (con != null) {
con.close();
}
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return chatrooms;
}
/**
* Retrieves a list of members in the chatroom.
*
* @return An ArrayList containing User instances representing members of the
* chatroom.
* @throws Exception If there is an issue retrieving members from the database.
*/
public ArrayList<User> showChatroomMembers() throws Exception {
ArrayList<User> members = new ArrayList<>();
try (DB db = new DB(); Connection con = db.getConnection()) {
try (PreparedStatement stmt = con.prepareStatement(
"SELECT AppUser.userId, AppUser.username, AppUser.pass_word, AppUser.country " +
"FROM AppUser " +
"JOIN ChatroomUser ON AppUser.userId = ChatroomUser.userId " +
"WHERE ChatroomUser.roomId = ?;")) {
stmt.setInt(1, roomId);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int userId = rs.getInt("userId");
String username = rs.getString("username");
String password = rs.getString("pass_word");
String country = rs.getString("country");
User user = new User(userId, username, password, country);
members.add(user);
}
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
return members;
}
/**
* Retrieves a list of messages in the chatroom.
*
* @return An ArrayList containing Message instances representing messages in
* the chatroom.
* @throws Exception If there is an issue retrieving messages from the database.
*/
public ArrayList<Message> getMessages() throws Exception {
ArrayList<Message> messages = new ArrayList<>();
try (
Connection con = new DB().getConnection();
PreparedStatement stmt = con.prepareStatement(
"SELECT id, Message.userId, text, spoiler, Message.username " +
"FROM Message " +
"JOIN AppUser ON Message.userId = AppUser.userId " +
"WHERE roomId=?");) {
stmt.setInt(1, roomId);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int messageId = rs.getInt("id");
int userId = rs.getInt("userId");
String messageText = rs.getString("text");
boolean spoiler = rs.getBoolean("spoiler");
String senderUsername = rs.getString("username");
Message message = new Message(messageId, userId, spoiler, messageText, roomId, senderUsername);
messages.add(message);
}
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return messages;
}
/**
* Retrieves unseen messages for a specific user in the chatroom and removes
* them from the unseen messages list.
*
* @param userId The user ID for which to retrieve unseen messages.
* @return An ArrayList containing Message instances representing unseen
* messages.
* @throws Exception If there is an issue retrieving or removing unseen messages
* from the database.
*/
public ArrayList<Message> getUnseenMessages(int userId) throws Exception {
ArrayList<Message> messages = new ArrayList<>();
try (DB db = new DB();
Connection con = db.getConnection();
PreparedStatement stmt1 = con.prepareStatement(
"SELECT Message.id, Message.userId, Message.text, Message.spoiler, AppUser.username " +
"FROM Message " +
"JOIN UnseenMessage ON UnseenMessage.UnSeenMessageId = Message.id " +
"JOIN AppUser ON Message.userId = AppUser.userId " +
"WHERE UnseenMessage.userId=? AND UnseenMessage.roomId =?");
PreparedStatement stmt2 = con.prepareStatement(
"DELETE FROM UnseenMessage WHERE UnseenMessage.userId=? AND UnseenMessage.roomId =?");) {
stmt1.setInt(1, userId);
stmt1.setInt(2, roomId);
try (ResultSet rs = stmt1.executeQuery()) {
while (rs.next()) {
int messageId = rs.getInt("id");
int senderUserId = rs.getInt("userId");
String messageText = rs.getString("text");
boolean spoiler = rs.getBoolean("spoiler");
String senderUsername = rs.getString("username");
Message message = new Message(messageId, senderUserId, spoiler, messageText, roomId,
senderUsername);
messages.add(message);
}
}
if (!messages.isEmpty()) {
stmt2.setInt(1, userId);
stmt2.setInt(2, roomId);
stmt2.executeUpdate();
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return messages;
}
/**
* Retrieves a chatroom by its name.
*
* @param chatroomName The name of the chatroom to retrieve.
* @return The Chatroom instance if found; otherwise, null.
* @throws Exception If there is an issue retrieving the chatroom from the
* database.
*/
public static Chatroom getChatroomByName(String chatroomName) throws Exception {
Chatroom chatroom = null;
try (DB db = new DB(); Connection con = db.getConnection()) {
String sql = "SELECT * FROM Chatroom WHERE name = ?";
try (PreparedStatement stmt = con.prepareStatement(sql)) {
stmt.setString(1, chatroomName);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
int roomId = rs.getInt("roomId");
int creatorId = rs.getInt("creatorId");
chatroom = new Chatroom(roomId, chatroomName, creatorId);
}
}
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return chatroom;
}
/**
* Checks if a user is a member of the chatroom.
*
* @param userId The user ID to check.
* @return True if the user is a member of the chatroom; otherwise, false.
* @throws Exception If there is an issue checking the user's membership in the
* database.
*/
public boolean isUserInChatroom(int userId) throws Exception {
try (DB db = new DB(); Connection con = db.getConnection()) {
String sql = "SELECT COUNT(*) FROM ChatroomUser WHERE roomId = ? AND userId = ?";
try (PreparedStatement stmt = con.prepareStatement(sql)) {
stmt.setInt(1, roomId);
stmt.setInt(2, userId);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return rs.getInt(1) > 0;
}
}
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return false;
}
/**
* Returns a string representation of the Chatroom object.
*
* @return A string containing the chatroom's details.
*/
@Override
public String toString() {
return "Chatroom{" +
"roomId=" + roomId +
", name='" + name + '\'' +
", createorId=" + creatorId +
'}';
}
}
| Aglag257/Java2_AIApp | app/src/main/java/gr/aueb/Chatroom.java |
45,571 | package makisp.gohome;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
/**
* Created by Ευάγγελος Πετρόπουλος on 26/11/2016.
*/
public class TestCredential {
Credential credential = new Credential(0, "Ευάγγελος", "123456", 1);
Credential setCredential = new Credential();
@Test
public void testGetId() throws Exception {
int id = credential.getId();
assertEquals(0,id);
}
@Test
public void testGetUsername() throws Exception {
String username = credential.getUsername();
assertEquals("Ευάγγελος", username);
}
@Test
public void testGetPassword() throws Exception {
String password = credential.getPassword();
assertEquals("123456", password);
}
@Test
public void testGetProgress() throws Exception {
int progress = credential.getProgress();
assertEquals(1, progress);
}
@Test
public void testSetGetId() throws Exception {
setCredential.setId(0);
int id = credential.getId();
assertEquals(0,id);
}
@Test
public void testSetGetUsername() throws Exception {
setCredential.setUsername("Ευάγγελος");
String username = credential.getUsername();
assertEquals("Ευάγγελος", username);
}
@Test
public void testSetGetPassword() throws Exception {
setCredential.setPassword("123456");
String password = credential.getPassword();
assertEquals("123456", password);
}
@Test
public void testSetGetProgress() throws Exception {
setCredential.setProgress(1);
int progress = credential.getProgress();
assertEquals(1, progress);
}
@Test
public void testGetIdIsNotNull() throws Exception {
int id = credential.getId();
assertNotNull(id);
}
@Test
public void testGetUsernameIsNotNull() throws Exception {
String username = credential.getUsername();
assertNotNull(username);
}
@Test
public void testGetPasswordIsNotNull() throws Exception {
String password = credential.getPassword();
assertNotNull(password);
}
@Test
public void testGetProgressIsNotNull() throws Exception {
int progress = credential.getProgress();
assertNotNull(progress);
}
}
| teicm-project/go-home | app/src/test/java/makisp/gohome/TestCredential.java |
45,572 | package makisp.gohome;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by Ευάγγελος Πετρόπουλος on 20/12/2016.
*/
///// JUnit Tests /////
public class TestMarkers {
Markers marker = new Markers();
Markers IDMarker = new Markers(1, 89.4, 78.3);
Markers withoutIDMarkers = new Markers(102.5, 156.3);
@Test
public void testMarkerIsNull(){
int expectedID = 0;
int actualID = marker.getId();
double actualLatitude = marker.getLatitude();
double actualLongitude = marker.getLongitude();
Assert.assertEquals(expectedID, actualID);
Assert.assertEquals(0.0, actualLatitude, 0.0-actualLatitude);
Assert.assertEquals(0.0, actualLongitude, 0.0-actualLongitude);
}
@Test
public void testIDMarkerIsNotNull(){
int expectedID = 1;
int actualID = IDMarker.getId();
double expectedLatitude = 89.4;
double actualLatitude = IDMarker.getLatitude();
double expectedLongitude = 78.3;
double actualLongitude = IDMarker.getLongitude();
Assert.assertEquals(expectedID, actualID);
Assert.assertEquals(expectedLatitude, actualLatitude, expectedLatitude-actualLatitude);
Assert.assertEquals(expectedLongitude, actualLongitude, expectedLongitude-actualLongitude);
}
@Test
public void testWithoutIDMarkerIsNotNull(){
int expectedID = 0;
int actualID = withoutIDMarkers.getId();
double expectedLatitude = 102.5;
double actualLatitude = withoutIDMarkers.getLatitude();
double expectedLongitude = 156.3;
double actualLongitude = withoutIDMarkers.getLongitude();
Assert.assertEquals(expectedID, actualID);
Assert.assertEquals(expectedLatitude, actualLatitude, expectedLatitude-actualLatitude);
Assert.assertEquals(expectedLongitude, actualLongitude, expectedLongitude-actualLongitude);
}
@Test
public void testSetInventory(){
marker.setId(10);
marker.setLatitude(555.5);
marker.setLongitude(98.6);
int expectedID = 10;
int actualID = marker.getId();
double expectedLatitude = 555.5;
double actualLatitude = marker.getLatitude();
double expectedLongitude = 98.6;
double actualLongitude = marker.getLongitude();
Assert.assertEquals(expectedID, actualID);
Assert.assertEquals(expectedLatitude, actualLatitude, expectedLatitude-actualLatitude);
Assert.assertEquals(expectedLongitude, actualLongitude, expectedLongitude-actualLongitude);
}
}
| teicm-project/go-home | app/src/test/java/makisp/gohome/TestMarkers.java |
45,586 | package com.mobile.physiolink.ui.popup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.transition.AutoTransition;
import android.transition.TransitionManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.mobile.physiolink.databinding.ItemDoctorPaymentPopUpBinding;
import com.mobile.physiolink.model.appointment.Appointment;
import com.mobile.physiolink.model.user.singleton.UserHolder;
import com.mobile.physiolink.service.api.API;
import com.mobile.physiolink.service.api.RequestFacade;
import com.mobile.physiolink.ui.doctor.adapter.AdapterForAppointments;
import com.mobile.physiolink.ui.doctor.viewmodel.DoctorServicesViewModel;
import com.mobile.physiolink.ui.patient.RecyclerItemClickListener;
import com.mobile.physiolink.ui.popup.adapter.AdapterForServicesPayment;
import com.mobile.physiolink.util.image.ProfileImageProvider;
import java.io.IOException;
import java.util.HashMap;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class AppointmentPaymentPopUp extends AppCompatDialogFragment {
private DoctorServicesViewModel servicesViewmodel;
private final String title;
private ItemDoctorPaymentPopUpBinding binding;
private AdapterForServicesPayment adapter;
private Appointment appointment;
private String newAppointmentHour;
private String newAppointmentName;
private DialogInterface.OnClickListener positiveListener;
private DialogInterface.OnClickListener negativeListener;
public AppointmentPaymentPopUp(Appointment appointment,
String appointmentHour,
String appointmentName,
FragmentActivity context,
AdapterForAppointments adapter, int position) {
title = "Καταχώρηση ραντεβού";
this.appointment = appointment;
this.newAppointmentHour = appointmentHour;
this.newAppointmentName = appointmentName;
setPositiveOnClick(((dialog, which) ->
{
HashMap<String, String> keyValues = new HashMap<>(3);
keyValues.put("appointment_id", String.valueOf(appointment.getId()));
keyValues.put("service_title", binding.serviceBtn.getText().toString());
keyValues.put("date", appointment.getDate());
RequestFacade.postRequest(API.ACCEPT_PAYMENT, keyValues, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (context == null)
return;
context.runOnUiThread(() ->
{
adapter.remove(position);
adapter.notifyItemRemoved(position);
Toast.makeText(context, "Έγινε επιτυχής καταχώρηση ραντεβού!",
Toast.LENGTH_SHORT).show();
});
}
});
}));
}
public void setPositiveOnClick(DialogInterface.OnClickListener listener) {
this.positiveListener = listener;
}
public void setNegativeOnClick(DialogInterface.OnClickListener listener) {
this.negativeListener = listener;
}
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
android.app.AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
binding = ItemDoctorPaymentPopUpBinding.inflate(requireActivity().getLayoutInflater());
builder.setTitle(title)
.setView(binding.getRoot())
.setPositiveButton("Καταχώρηση", positiveListener)
.setNegativeButton("Ακύρωση", negativeListener);
binding.appointmentTimeDoctorPatient.setText(newAppointmentHour);
binding.appointmentNameDoctorPatient.setText(newAppointmentName);
return builder.create();
}
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
servicesViewmodel = new ViewModelProvider(this).get(DoctorServicesViewModel.class);
servicesViewmodel.getDoctorServices().observe(getViewLifecycleOwner(), services ->
adapter.setServices(services));
ProfileImageProvider.setImageOfAppointment(binding.patientImageDoctorAppointment,
appointment);
return binding.getRoot();
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
servicesViewmodel.loadDoctorServices(UserHolder.doctor().getId());
adapter = new AdapterForServicesPayment();
binding.servicesPaymentList.setAdapter(adapter);
binding.servicesPaymentList.setLayoutManager(new LinearLayoutManager(this.getContext()));
binding.serviceBtn.setOnClickListener(view1 ->
{
if (binding.servicesPaymentList.getVisibility() == View.GONE) {
TransitionManager.beginDelayedTransition(binding.chooseServicePaymentCardView, new AutoTransition());
binding.servicesPaymentList.setVisibility(View.VISIBLE);
} else {
TransitionManager.beginDelayedTransition(binding.chooseServicePaymentCardView, new AutoTransition());
binding.servicesPaymentList.setVisibility(View.GONE);
}
});
binding.servicesPaymentList.addOnItemTouchListener(
new RecyclerItemClickListener(this.getContext(), binding.servicesPaymentList, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
binding.serviceBtn.setText(adapter.getServices().get(position).getTitle());
binding.servicePricePayment.setText(String.valueOf((int) adapter.getServices().get(position).getPrice())+"€");
binding.servicesPaymentList.setVisibility(View.GONE);
}
@Override
public void onLongItemClick(View view, int position) {
}
})
);
}
} | setokk/PhysioLink | app/src/main/java/com/mobile/physiolink/ui/popup/AppointmentPaymentPopUp.java |
45,599 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package projectt;
import icons.FontAwesome;
import jiconfont.swing.IconFontSwing;
import java.awt.Color;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import net.proteanit.sql.DbUtils;
/**
*
* @author Nikolas
*/
public class Vaccines_Manager extends javax.swing.JFrame {
int presence_counter=0, absence_counter=0;
/**
* Creates new form Vaccines_Manager
*/
public Vaccines_Manager() {
IconFontSwing.register(FontAwesome.getIconFont());
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jTextField1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
DateChooser = new com.toedter.calendar.JDateChooser();
jScrollPane1 = new javax.swing.JScrollPane();
myTable = new javax.swing.JTable();
search_button = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
presence = new javax.swing.JButton();
absence = new javax.swing.JButton();
jTextField4 = new javax.swing.JTextField();
jTextField5 = new javax.swing.JTextField();
counter_2 = new javax.swing.JLabel();
counter_1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(150, 235, 240));
jPanel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField1.setBackground(new java.awt.Color(150, 235, 240));
jTextField1.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jTextField1.setText("Ραντεβού Εμβολιασμών");
jTextField1.setBorder(null);
jTextField1.setFocusable(false);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/A4AD5659B5D44610AB530DF0BAB8279D.jpeg"))); // NOI18N
jLabel1.setText("jLabel1");
jTextField2.setBackground(new java.awt.Color(150, 235, 240));
jTextField2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField2.setText("Ημερομηνία");
jTextField2.setBorder(null);
jTextField2.setFocusable(false);
myTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Ονοματεπώνυμο", "Ώρα", "Εμβόλιο"
}
)
{
public boolean isCellEditable(int row, int column) {
return false;
}
}
);
myTable.setDefaultEditor(Object.class, null);
myTable.setSelectionForeground(new java.awt.Color(255, 255, 255));
jScrollPane1.setViewportView(myTable);
myTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
search_button.setBackground(new java.awt.Color(0, 0, 0));
search_button.setForeground(new java.awt.Color(255, 255, 255));
search_button.setText("Αναζήτηση");
search_button.setBorder(null);
search_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
search_buttonActionPerformed(evt);
}
});
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/emvolio.jpg"))); // NOI18N
presence.setIcon(IconFontSwing.buildIcon(FontAwesome.CHECK_SQUARE_O, 50, Color.black));
presence.setBorderPainted(false);
presence.setContentAreaFilled(false);
presence.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
presenceActionPerformed(evt);
}
});
absence.setIcon(IconFontSwing.buildIcon(FontAwesome.WINDOW_CLOSE_O, 50, Color.black));
absence.setToolTipText("");
absence.setBorderPainted(false);
absence.setContentAreaFilled(false);
absence.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
absenceActionPerformed(evt);
}
});
jTextField4.setBackground(new java.awt.Color(150, 235, 240));
jTextField4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField4.setText("Προσήλθαν ");
jTextField4.setBorder(null);
jTextField4.setFocusable(false);
jTextField5.setBackground(new java.awt.Color(150, 235, 240));
jTextField5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTextField5.setText("Δεν προσήλθαν ");
jTextField5.setBorder(null);
jTextField5.setFocusable(false);
counter_2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
counter_2.setText("0");
counter_2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
counter_1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
counter_1.setText("0");
counter_1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel4.setText("/");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(DateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(37, 37, 37)
.addComponent(search_button, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 507, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 913, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(32, 32, 32)
.addComponent(presence, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(counter_1)
.addGap(46, 46, 46))
.addComponent(jTextField4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(absence, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(jLabel4)
.addGap(46, 46, 46)
.addComponent(counter_2))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(15, Short.MAX_VALUE))))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(DateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(search_button, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(9, 9, 9)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE)
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(absence, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(presence, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(86, 86, 86)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(counter_1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(counter_2, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 104, Short.MAX_VALUE)
.addComponent(jLabel2))))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void getVacAppointments() {
try {
LogIn_Staff login_staff = new LogIn_Staff();
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", "");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(DateChooser.getDate());
String user_id = login_staff.staff_userId();
String sql = "SELECT CONCAT(first_name,' ',last_name) AS Ονοματεπώνυμο, date_format(app_date,'%H:%i') AS Ώρα, vaccine_title As Εμβόλιο FROM appointment INNER JOIN user on patient_id=user_id INNER JOIN covid_vaccine ON app_id=vacc_app_id WHERE DATE(app_date)='" + date + "' AND vacc_man_id='" + user_id + "' ";
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if (!rs.isBeforeFirst()) {
//DateChooser.setCalendar(null);
myTable.setModel(new DefaultTableModel(null, new String[]{"Ονοματεπώνυμο", "Ώρα", "Εμβόλιο"}));
JOptionPane.showMessageDialog(this, "Δεν υπάρχουν ραντεβού για αυτή την ημερομηνία.");
} else {
myTable.setModel(DbUtils.resultSetToTableModel(rs));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void absenceCounter() {
DefaultTableModel tablemodel = (DefaultTableModel) myTable.getModel();
if (myTable.getSelectedRow() != -1) {
absence_counter++;
counter_2.setText(" " + absence_counter);
tablemodel.removeRow(myTable.getSelectedRow());
} else {
JOptionPane.showMessageDialog(this, "Επιλέξτε ραντεβού!");
}
}
private void presenceCounter() {
DefaultTableModel tablemodel = (DefaultTableModel) myTable.getModel();
if (myTable.getSelectedRow() != -1) {
presence_counter++;
counter_1.setText(" " + presence_counter);
tablemodel.removeRow(myTable.getSelectedRow());
} else {
JOptionPane.showMessageDialog(this, "Επιλέξτε ραντεβού!");
}
}
private void absenceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_absenceActionPerformed
absenceCounter();
}//GEN-LAST:event_absenceActionPerformed
private void presenceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_presenceActionPerformed
presenceCounter();
}//GEN-LAST:event_presenceActionPerformed
private void search_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_search_buttonActionPerformed
if(DateChooser.getDate() == null) {
JOptionPane.showMessageDialog(this,("Επιλέξτε ημερομηνία!"));
}
else {
getVacAppointments();
}
}//GEN-LAST:event_search_buttonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Vaccines_Manager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Vaccines_Manager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Vaccines_Manager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Vaccines_Manager.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Vaccines_Manager().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private com.toedter.calendar.JDateChooser DateChooser;
private javax.swing.JButton absence;
private javax.swing.JLabel counter_1;
private javax.swing.JLabel counter_2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTable myTable;
private javax.swing.JButton presence;
private javax.swing.JButton search_button;
// End of variables declaration//GEN-END:variables
}
| alexkou/Software_Engineering_Project | src/projectt/Vaccines_Manager.java |
45,616 | package org.elasticsearch.index.analysis;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.Assert;
public class GreeklishReverseStemmerTest {
/**
* Some greek words whose variations we want to produce.
*/
private static final String[] greekWords = {
"κουρεματοσ", "ενδυματα", "γραφειου", "πεδιου",
"γραναζι", "ποδηλατα", "καλωδιων"
};
/**
* Words that should not match to any rule.
*/
private static final String[] nonMatchingWords = {
"σουτιεν", "κολλαν", "αμπαλαζ", "μακιγιαζ"
};
/**
* The output we expect for each of the above words.
*/
private static final String[][] greekVariants = {
{"κουρεμα", "κουρεματων", "κουρεματα"},
{"ενδυμα", "ενδυματων", "ενδυματα", "ενδυματοσ"},
{"γραφειο", "γραφεια", "γραφειων"},
{"πεδια", "πεδιο", "πεδιων"},
{"γραναζια", "γραναζιου", "γραναζιων"},
{"ποδηλατο", "ποδηλατου", "ποδηλατα", "ποδηλατων"},
{"καλωδιου", "καλωδια", "καλωδιο"}
};
private GreekReverseStemmer reverseStemmer;
private List<String> generatedGreekVariants;
@BeforeClass
public void setUp() {
this.reverseStemmer = new GreekReverseStemmer();
this.generatedGreekVariants = new ArrayList<String>();
}
@BeforeMethod
public void clearThePreviousResults() {
generatedGreekVariants.clear();
}
@Test
public void testGenerationOfGreekVariants() {
for (int i = 0; i < greekWords.length; i++) {
generatedGreekVariants = reverseStemmer.generateGreekVariants(greekWords[i]);
Assert.assertTrue(generatedGreekVariants.size() > 1, "The reverse stemmer should produce results");
for (String greekVariant : greekVariants[i]) {
Assert.assertTrue(generatedGreekVariants.contains(greekVariant),
"It should contain the greek variant: " + greekVariant);
}
}
}
@Test
public void testNonMatchingWords() {
for (String nonMatchingWord : nonMatchingWords) {
generatedGreekVariants = reverseStemmer.generateGreekVariants(nonMatchingWord);
Assert.assertTrue(generatedGreekVariants.size() == 1, "The reverse stemmer should not produce more results");
}
}
}
| skroutz/elasticsearch-analysis-greeklish | src/test/java/org/elasticsearch/index/analysis/GreeklishReverseStemmerTest.java |
45,667 | /*
* Copyright (c) 2017, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
package com.force.i18n.grammar.parser;
import java.util.Locale;
import com.force.i18n.*;
/**
* @author stamm
*/
public class GrammaticalLabelFileTest extends BaseGrammaticalLabelTest {
public GrammaticalLabelFileTest(String name) {
super(name);
}
public void testEnglishArticles() throws Exception {
final HumanLanguage ENGLISH = LanguageProviderFactory.get().getLanguage(Locale.US);
final HumanLanguage ENGLISH_CA = LanguageProviderFactory.get().getLanguage(Locale.CANADA);
assertEquals("This quote can't be synced because it has an inactive or archived price book.",
renderLabel(ENGLISH, "<This/> <quote/> can't be synced because it has <a/> <inactive/> or <archived/> <pricebook/>.", null));
assertEquals("Ask a Question", renderLabel(ENGLISH, "Ask <a/> <Question/>", null));
assertEquals("Ask a Question", renderLabel(ENGLISH_CA, "Ask <a/> <Question/>", null));
}
public void testGermanArticles() throws Exception {
final HumanLanguage GERMAN = LanguageProviderFactory.get().getLanguage("de");
// Validate that the definitiveness passes throughout the whole thing
assertEquals("Die Neuen Accounts", renderLabel(GERMAN, "<The/> <New/> <Accounts/>", null));
assertEquals("Der Neue Account", renderLabel(GERMAN, "<The/> <New/> <Account/>", null));
assertEquals("Ein Neuer Account", renderLabel(GERMAN, "<A/> <New/> <Account/>", null));
assertEquals("Ein Neuer Account und Ein Neues Dokument und Eine Neue Kampagne", renderLabel(GERMAN, "<A/> <New/> <Account/> und <A/> <New/> <Document/> und <A/> <New/> <Campaign/>", null));
assertEquals("Einem neuem Account und Einem neuem Dokument und Einer neuer Kampagne", renderLabel(GERMAN, "<A/> <New/> <Account case='d'/> und <A/> <New/> <Document case='d'/> und <A/> <New/> <Campaign case='d'/>", null));
// tests article override in adjectives
assertEquals("Ein Anderer Account", renderLabel(GERMAN, "<A/> <Other article=\"the\"/> <Account/>", null));
}
public void testLegacyArticleForm() throws Exception {
final HumanLanguage ENGLISH = LanguageProviderFactory.get().getLanguage(Locale.US);
final HumanLanguage ITALIAN = LanguageProviderFactory.get().getLanguage("it");
final HumanLanguage GERMAN = LanguageProviderFactory.get().getLanguage("de");
// This tests some old crappy behavior in label files. Don't use this
assertEquals("An account", renderLabel(ENGLISH, "<Account article=\"a\"/>", null));
assertEquals("The account", renderLabel(ENGLISH, "<Account article=\"the\"/>", null));
assertEquals("Un account", renderLabel(ITALIAN, "<Account article=\"a\"/>", null));
assertEquals("L'account", renderLabel(ITALIAN, "<Account article=\"the\"/>", null));
// Note, in german the nouns are always capitalized. Always
assertEquals("Ein Account", renderLabel(GERMAN, "<Account article=\"a\"/>", null));
assertEquals("Der Account", renderLabel(GERMAN, "<Account article=\"the\"/>", null));
assertEquals("Einem Account", renderLabel(GERMAN, "<Account article=\"a\" case=\"d\"/>", null));
assertEquals("Dem Account", renderLabel(GERMAN, "<Account article=\"the\" case=\"d\"/>", null));
}
/**
* There are two lowercase sigmas for Greek (σ and ς), depending on where in the word the sigma appears
* Make sure that these remain unchanged on case-folding, and that upper-case sigma (Σ) folds to
* the right character, which should be σ since we only capitalize the first letter in sfdcnames.xml
* and sfdcadjectives.xml
*/
public void testGreekSigma() throws Exception {
final HumanLanguage GREEK = LanguageProviderFactory.get().getLanguage(LanguageConstants.GREEK);
// lowercase sigmas should remain unchanged with case folding
assertEquals("Ανοιχτές Εργασίες", renderLabel(GREEK, "<Open/> <Tasks case=\"a\"/>"));
assertEquals("ανοιχτές εργασίες", renderLabel(GREEK, "<open/> <tasks case=\"a\"/>"));
assertEquals("Ανοιχτή Εργασία", renderLabel(GREEK, "<Open/> <Task case=\"a\"/>"));
assertEquals("ανοιχτή εργασία", renderLabel(GREEK, "<open/> <task case=\"a\"/>"));
// uppercase sigma should correctly fold to lowercase sigma;
// we never have all-cap words in sfdcnames.xml and sfdcadjectives.xml, so don't need to worry
// about folding uppercase sigma to word-final sigma
assertEquals("Συσχετισμένη Εκστρατεία", renderLabel(GREEK, "<Associated/> <Campaign/>"));
assertEquals("συσχετισμένη εκστρατεία", renderLabel(GREEK, "<associated/> <campaign/>"));
}
public void testVietnamese() throws Exception {
final HumanLanguage VIETNAMESE = LanguageProviderFactory.get().getLanguage(LanguageConstants.VIETNAMESE);
// Unlike other asian language, Vietnamese has upper/lower case letters
assertEquals("Khách Hàng Tiềm Năng", renderLabel(VIETNAMESE, "<Lead/>"));
assertEquals("khách hàng tiềm năng", renderLabel(VIETNAMESE, "<lead/>"));
assertEquals("Khách Hàng Tiềm Năng", renderDynamicLabel(VIETNAMESE, "<Entity entity=\"0\"/>", getStandardRenameable("lead")));
assertEquals("khách hàng tiềm năng", renderDynamicLabel(VIETNAMESE, "<entity entity=\"0\"/>", getStandardRenameable("lead")));
assertEquals("Tài Liệu", renderLabel(VIETNAMESE, "<Document/>"));
assertEquals("Các Tài Liệu", renderLabel(VIETNAMESE, "<Documents/>"));
}
// TODO: what is this for? seems like its just reporting on terminal for missing plural form in names.xml.
// it's not validatin/asserting; disable it for now.
// public void testDifferenceInRenameTabs() throws Exception {
// StringBuilder diffs = new StringBuilder();
// for (HumanLanguage language : LanguageProviderFactory.get().getAll()) {
// if (!LanguageDeclensionFactory.get().getDeclension(language).hasPlural()) continue;
// LanguageDictionary dictionary = loadDictionary(language);
// Multimap<String,String> nowHasPlural = TreeMultimap.create();
// Multimap<String,String> missingPlural = TreeMultimap.create();
// for (String entity : new TreeSet<String>(dictionary.getNounsByEntity().keySet())) {
// for (Noun n : dictionary.getNounsByEntity().get(entity)) {
// if (n.getNounType() == NounType.ENTITY) continue;
// boolean hasPluralForm = false;
// for (NounForm form : n.getAllDefinedValues().keySet()) {
// if (form.getNumber() == LanguageNumber.PLURAL && form.getCase() == LanguageCase.NOMINATIVE) {
// hasPluralForm = true;
// break;
// }
// }
// if (hasPluralForm != (n.getNounType() == NounType.FIELD)) {
// if (hasPluralForm) {
// nowHasPlural.put(entity, n.getName());
// } else {
// missingPlural.put(entity, n.getName());
// }
// }
// }
// }
// if (nowHasPlural.size() > 0) {
// diffs.append(language).append(" can rename plural fields for: ").append(nowHasPlural).append('\n');
// }
// if (missingPlural.size() > 0) {
// diffs.append(language).append(" has these plural fields removed for rename: ").append(missingPlural).append('\n');
// }
// }
// System.out.println(diffs.toString());
// }
}
| salesforce/grammaticus | src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelFileTest.java |
45,668 | /*
* Copyright (c) 2017, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
package com.force.i18n.grammar.parser;
import java.util.Locale;
import java.util.TreeSet;
import com.force.i18n.*;
import com.force.i18n.grammar.*;
import com.force.i18n.grammar.Noun.NounType;
import com.force.i18n.grammar.impl.LanguageDeclensionFactory;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
/**
* @author stamm
*/
public class GrammaticalLabelFileTest extends BaseGrammaticalLabelTest {
public GrammaticalLabelFileTest(String name) {
super(name);
}
public void testEnglishArticles() throws Exception {
final HumanLanguage ENGLISH = LanguageProviderFactory.get().getLanguage(Locale.US);
final HumanLanguage ENGLISH_CA = LanguageProviderFactory.get().getLanguage(Locale.CANADA);
assertEquals("This quote can't be synced because it has an inactive or archived price book.",
renderLabel(ENGLISH, "<This/> <quote/> can't be synced because it has <a/> <inactive/> or <archived/> <pricebook/>.", null));
assertEquals("Ask a Question", renderLabel(ENGLISH, "Ask <a/> <Question/>", null));
assertEquals("Ask a Question", renderLabel(ENGLISH_CA, "Ask <a/> <Question/>", null));
}
public void testGermanArticles() throws Exception {
final HumanLanguage GERMAN = LanguageProviderFactory.get().getLanguage("de");
// Validate that the definitiveness passes throughout the whole thing
assertEquals("Die Neuen Accounts", renderLabel(GERMAN, "<The/> <New/> <Accounts/>", null));
assertEquals("Der Neue Account", renderLabel(GERMAN, "<The/> <New/> <Account/>", null));
assertEquals("Ein Neuer Account", renderLabel(GERMAN, "<A/> <New/> <Account/>", null));
assertEquals("Ein Neuer Account und Ein Neues Dokument und Eine Neue Kampagne", renderLabel(GERMAN, "<A/> <New/> <Account/> und <A/> <New/> <Document/> und <A/> <New/> <Campaign/>", null));
assertEquals("Einem neuem Account und Einem neuem Dokument und Einer neuer Kampagne", renderLabel(GERMAN, "<A/> <New/> <Account case='d'/> und <A/> <New/> <Document case='d'/> und <A/> <New/> <Campaign case='d'/>", null));
}
public void testLegacyArticleForm() throws Exception {
final HumanLanguage ENGLISH = LanguageProviderFactory.get().getLanguage(Locale.US);
final HumanLanguage ITALIAN = LanguageProviderFactory.get().getLanguage("it");
final HumanLanguage GERMAN = LanguageProviderFactory.get().getLanguage("de");
// This tests some old crappy behavior in label files. Don't use this
assertEquals("An account", renderLabel(ENGLISH, "<Account article=\"a\"/>", null));
assertEquals("The account", renderLabel(ENGLISH, "<Account article=\"the\"/>", null));
assertEquals("Un account", renderLabel(ITALIAN, "<Account article=\"a\"/>", null));
assertEquals("L'account", renderLabel(ITALIAN, "<Account article=\"the\"/>", null));
// Note, in german the nouns are always capitalized. Always
assertEquals("Ein Account", renderLabel(GERMAN, "<Account article=\"a\"/>", null));
assertEquals("Der Account", renderLabel(GERMAN, "<Account article=\"the\"/>", null));
assertEquals("Einem Account", renderLabel(GERMAN, "<Account article=\"a\" case=\"d\"/>", null));
assertEquals("Dem Account", renderLabel(GERMAN, "<Account article=\"the\" case=\"d\"/>", null));
}
/**
* There are two lowercase sigmas for Greek (σ and ς), depending on where in the word the sigma appears
* Make sure that these remain unchanged on case-folding, and that upper-case sigma (Σ) folds to
* the right character, which should be σ since we only capitalize the first letter in sfdcnames.xml
* and sfdcadjectives.xml
*/
public void testGreekSigma() throws Exception {
final HumanLanguage GREEK = LanguageProviderFactory.get().getLanguage(LanguageConstants.GREEK);
// lowercase sigmas should remain unchanged with case folding
assertEquals("Ανοιχτές Εργασίες", renderLabel(GREEK, "<Open/> <Tasks case=\"a\"/>"));
assertEquals("ανοιχτές εργασίες", renderLabel(GREEK, "<open/> <tasks case=\"a\"/>"));
assertEquals("Ανοιχτή Εργασία", renderLabel(GREEK, "<Open/> <Task case=\"a\"/>"));
assertEquals("ανοιχτή εργασία", renderLabel(GREEK, "<open/> <task case=\"a\"/>"));
// uppercase sigma should correctly fold to lowercase sigma;
// we never have all-cap words in sfdcnames.xml and sfdcadjectives.xml, so don't need to worry
// about folding uppercase sigma to word-final sigma
assertEquals("Συσχετισμένη Εκστρατεία", renderLabel(GREEK, "<Associated/> <Campaign/>"));
assertEquals("συσχετισμένη εκστρατεία", renderLabel(GREEK, "<associated/> <campaign/>"));
}
public void testDifferenceInRenameTabs() throws Exception {
StringBuilder diffs = new StringBuilder();
for (HumanLanguage language : LanguageProviderFactory.get().getAll()) {
if (!LanguageDeclensionFactory.get().getDeclension(language).hasPlural()) continue;
LanguageDictionary dictionary = loadDictionary(language);
Multimap<String,String> nowHasPlural = TreeMultimap.create();
Multimap<String,String> missingPlural = TreeMultimap.create();
for (String entity : new TreeSet<String>(dictionary.getNounsByEntity().keySet())) {
for (Noun n : dictionary.getNounsByEntity().get(entity)) {
if (n.getNounType() == NounType.ENTITY) continue;
boolean hasPluralForm = false;
for (NounForm form : n.getAllDefinedValues().keySet()) {
if (form.getNumber() == LanguageNumber.PLURAL && form.getCase() == LanguageCase.NOMINATIVE) {
hasPluralForm = true;
break;
}
}
if (hasPluralForm != (n.getNounType() == NounType.FIELD)) {
if (hasPluralForm) {
nowHasPlural.put(entity, n.getName());
} else {
missingPlural.put(entity, n.getName());
}
}
}
}
if (nowHasPlural.size() > 0) {
diffs.append(language).append(" can rename plural fields for: ").append(nowHasPlural).append('\n');
}
if (missingPlural.size() > 0) {
diffs.append(language).append(" has these plural fields removed for rename: ").append(missingPlural).append('\n');
}
}
System.out.println(diffs.toString());
}
}
| seratch/grammaticus | src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelFileTest.java |
45,669 | /*
* Copyright (c) 2017, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
package com.force.i18n.grammar.parser;
import java.util.Locale;
import java.util.TreeSet;
import com.force.i18n.*;
import com.force.i18n.grammar.*;
import com.force.i18n.grammar.Noun.NounType;
import com.force.i18n.grammar.impl.LanguageDeclensionFactory;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
/**
* @author stamm
*/
public class GrammaticalLabelFileTest extends BaseGrammaticalLabelTest {
public GrammaticalLabelFileTest(String name) {
super(name);
}
public void testEnglishArticles() throws Exception {
final HumanLanguage ENGLISH = LanguageProviderFactory.get().getLanguage(Locale.US);
final HumanLanguage ENGLISH_CA = LanguageProviderFactory.get().getLanguage(Locale.CANADA);
assertEquals("This quote can't be synced because it has an inactive or archived price book.",
renderLabel(ENGLISH, "<This/> <quote/> can't be synced because it has <a/> <inactive/> or <archived/> <pricebook/>.", null));
assertEquals("Ask a Question", renderLabel(ENGLISH, "Ask <a/> <Question/>", null));
assertEquals("Ask a Question", renderLabel(ENGLISH_CA, "Ask <a/> <Question/>", null));
}
public void testGermanArticles() throws Exception {
final HumanLanguage GERMAN = LanguageProviderFactory.get().getLanguage("de");
// Validate that the definitiveness passes throughout the whole thing
assertEquals("Die Neuen Accounts", renderLabel(GERMAN, "<The/> <New/> <Accounts/>", null));
assertEquals("Der Neue Account", renderLabel(GERMAN, "<The/> <New/> <Account/>", null));
assertEquals("Ein Neuer Account", renderLabel(GERMAN, "<A/> <New/> <Account/>", null));
assertEquals("Ein Neuer Account und Ein Neues Dokument und Eine Neue Kampagne", renderLabel(GERMAN, "<A/> <New/> <Account/> und <A/> <New/> <Document/> und <A/> <New/> <Campaign/>", null));
assertEquals("Einem neuem Account und Einem neuem Dokument und Einer neuer Kampagne", renderLabel(GERMAN, "<A/> <New/> <Account case='d'/> und <A/> <New/> <Document case='d'/> und <A/> <New/> <Campaign case='d'/>", null));
// tests article override in adjectives
assertEquals("Ein Anderer Account", renderLabel(GERMAN, "<A/> <Other article=\"the\"/> <Account/>", null));
}
public void testLegacyArticleForm() throws Exception {
final HumanLanguage ENGLISH = LanguageProviderFactory.get().getLanguage(Locale.US);
final HumanLanguage ITALIAN = LanguageProviderFactory.get().getLanguage("it");
final HumanLanguage GERMAN = LanguageProviderFactory.get().getLanguage("de");
// This tests some old crappy behavior in label files. Don't use this
assertEquals("An account", renderLabel(ENGLISH, "<Account article=\"a\"/>", null));
assertEquals("The account", renderLabel(ENGLISH, "<Account article=\"the\"/>", null));
assertEquals("Un account", renderLabel(ITALIAN, "<Account article=\"a\"/>", null));
assertEquals("L'account", renderLabel(ITALIAN, "<Account article=\"the\"/>", null));
// Note, in german the nouns are always capitalized. Always
assertEquals("Ein Account", renderLabel(GERMAN, "<Account article=\"a\"/>", null));
assertEquals("Der Account", renderLabel(GERMAN, "<Account article=\"the\"/>", null));
assertEquals("Einem Account", renderLabel(GERMAN, "<Account article=\"a\" case=\"d\"/>", null));
assertEquals("Dem Account", renderLabel(GERMAN, "<Account article=\"the\" case=\"d\"/>", null));
}
/**
* There are two lowercase sigmas for Greek (σ and ς), depending on where in the word the sigma appears
* Make sure that these remain unchanged on case-folding, and that upper-case sigma (Σ) folds to
* the right character, which should be σ since we only capitalize the first letter in sfdcnames.xml
* and sfdcadjectives.xml
*/
public void testGreekSigma() throws Exception {
final HumanLanguage GREEK = LanguageProviderFactory.get().getLanguage(LanguageConstants.GREEK);
// lowercase sigmas should remain unchanged with case folding
assertEquals("Ανοιχτές Εργασίες", renderLabel(GREEK, "<Open/> <Tasks case=\"a\"/>"));
assertEquals("ανοιχτές εργασίες", renderLabel(GREEK, "<open/> <tasks case=\"a\"/>"));
assertEquals("Ανοιχτή Εργασία", renderLabel(GREEK, "<Open/> <Task case=\"a\"/>"));
assertEquals("ανοιχτή εργασία", renderLabel(GREEK, "<open/> <task case=\"a\"/>"));
// uppercase sigma should correctly fold to lowercase sigma;
// we never have all-cap words in sfdcnames.xml and sfdcadjectives.xml, so don't need to worry
// about folding uppercase sigma to word-final sigma
assertEquals("Συσχετισμένη Εκστρατεία", renderLabel(GREEK, "<Associated/> <Campaign/>"));
assertEquals("συσχετισμένη εκστρατεία", renderLabel(GREEK, "<associated/> <campaign/>"));
}
public void testDifferenceInRenameTabs() throws Exception {
StringBuilder diffs = new StringBuilder();
for (HumanLanguage language : LanguageProviderFactory.get().getAll()) {
if (!LanguageDeclensionFactory.get().getDeclension(language).hasPlural()) continue;
LanguageDictionary dictionary = loadDictionary(language);
Multimap<String,String> nowHasPlural = TreeMultimap.create();
Multimap<String,String> missingPlural = TreeMultimap.create();
for (String entity : new TreeSet<String>(dictionary.getNounsByEntity().keySet())) {
for (Noun n : dictionary.getNounsByEntity().get(entity)) {
if (n.getNounType() == NounType.ENTITY) continue;
boolean hasPluralForm = false;
for (NounForm form : n.getAllDefinedValues().keySet()) {
if (form.getNumber() == LanguageNumber.PLURAL && form.getCase() == LanguageCase.NOMINATIVE) {
hasPluralForm = true;
break;
}
}
if (hasPluralForm != (n.getNounType() == NounType.FIELD)) {
if (hasPluralForm) {
nowHasPlural.put(entity, n.getName());
} else {
missingPlural.put(entity, n.getName());
}
}
}
}
if (nowHasPlural.size() > 0) {
diffs.append(language).append(" can rename plural fields for: ").append(nowHasPlural).append('\n');
}
if (missingPlural.size() > 0) {
diffs.append(language).append(" has these plural fields removed for rename: ").append(missingPlural).append('\n');
}
}
System.out.println(diffs.toString());
}
}
| isabella232/grammaticus | src/test/java/com/force/i18n/grammar/parser/GrammaticalLabelFileTest.java |
45,673 | //DIONYSIOS THEODOSIS AM:321/2015066 2H OMADIKH KATANEMHMENA
package server2;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import shared.Flight;
import shared.FlightBooking;
import shared.FlightSearchCrit;
//KLASH H OPOIA YLOPIEI THN SYNDESH ME THN VASH KATHWS KAI TA ERWTHMATA
public class DatabaseManager {
//DILWSH PARAMETRWN KLASHS
private Connection connection; //PARAMETROS GIA THN SYNDESH ME THN VASH
private final String databaseUrl; //METAVLITH GIA TO URL THS VASHS
//CONSTRUCTOR THS KLASHS POU PERNEI WS ORISMA TO URL
public DatabaseManager(String databaseUrl) {
this.databaseUrl=databaseUrl;
}
//METHODOS THS VASHS GIA THN SYNDESH
public void connect() throws SQLException {
connection = DriverManager.getConnection(databaseUrl);
}
//METHODOS GIA THN APOSYNDESH APO THN VASH
public void disconnect() throws SQLException {
if (connection != null) { //ELEGXEI AN YPARXEI SYNDESH
connection.close(); //KLEINEI THN SYNDESH
}
}
//METHODOS GIA THN EISAGWGH EGGRAFHS STHN VASH KAI DEXETAI WS ORISMA ENA ANTIKEIMENO POU PERIEXEI TIS MATAVLITES GIA THN KRATHSH
public String insertData(FlightBooking bookedCred) throws SQLException {
//FTIAXNOUME TO STRING GIA TO SQL QUERY
String sql = "INSERT INTO BookedFlights (outbound_flight_id, return_flight_id, price, passengers) VALUES (?, ?, ?, ?)";
int generatedId = -1; //THETOUME MIA DEFAULT METAVLITH SE PERIPTWSH POU DEN GINEI H EGGRAFH KAI DEN VRETHEI KLIDI
//FTIAXNOUME TO PREPAREDSTATEMENT
try (PreparedStatement stmt = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
//KANOUME ELEGXO AN EINAI TAXIDI XWRIS EPISTROFH KAI AN EINAI KANOUME THN KRATHSH GIA TO TAXIDI ME APLH PTHSH
if (bookedCred.getReturnFlight() == null) {
//ELEGXOUME AN YPARXOUN DIATHESIMES THESEIS GIA THN PRWTH PTHSH
int availableSeats = getAvailableSeats(bookedCred.getOutboundFlight().getFlightId()); //PERNOUME TON ARITHMO TWN DIATHESIMWN THESEWN
if (bookedCred.getPassengers() <= availableSeats) { //EXETAZOUME AN OI EPIVATES EINAI LIGOTEROI H ISOI APO TIS DIATHESIMES THESEIS
//THETOUME TIS TIMES STO PREPARED STATEMENT
stmt.setInt(1, bookedCred.getOutboundFlight().getFlightId()); //TO ID THS PTHSHS
stmt.setNull(2, Types.INTEGER); //THETOUME WS NULL TO ID THS PTHSHS EPISTROFHS
stmt.setDouble(3, bookedCred.getPrice()); //THETOUME THN TIMH
stmt.setInt(4, bookedCred.getPassengers()); //THETOUME TOUS EPIVATES
//TREXOUME TO STATEMENT KAI PERNOUME NA DOUME AN EPIREASTIKAN OI GRAMMES
int rowsAffected = stmt.executeUpdate();
if (rowsAffected == 1) { //EDW TSEKAROUME AN EPIREASTIKAN
//VRYSKOUME TO ID THS PTHSHS
ResultSet generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next()) {
generatedId = generatedKeys.getInt(1);
}
}
return ("Η κράτηση έγινε επιτυχώς\nΚωδικός κράτησης : " + generatedId);//EPISTREFOUME TO MINIMA
} else {
return ("Δεν υπάρχουν διαθέσιμες θέσεις για την πτήση.");//EPISTREFOUME TO MINIMA
}
} else { //GIA THN PERIPTWSH POU EINAI ME EPISTROFH
// PERNOUME TIS DIATHESIMES THESEIS GIA THN PTHSH THS ANAXWRHSHS
int availableOutboundSeats = getAvailableSeats(bookedCred.getOutboundFlight().getFlightId());
//PERNOUME TIS DIATHESIMES THESEIS GIA THN PTHSH THS EPISTREOFHS
int availableReturnSeats = getAvailableSeats(bookedCred.getReturnFlight().getFlightId());
//ELEGXOUME AN YPARXOUN DIATHESIMES THESEIS KAI GIA TIS 2 PTHSEIS
if (bookedCred.getPassengers() <= availableOutboundSeats && bookedCred.getPassengers() <= availableReturnSeats) {
//THETOUME TIS TIMES GIA TO PREPAREDSTATEMENT
stmt.setInt(1, bookedCred.getOutboundFlight().getFlightId()); //TO ID TIS PTHSHS ANAXWRHSHS
stmt.setInt(2, bookedCred.getReturnFlight().getFlightId()); //TO ID THS PTHSHS THS EPISTROFHS
stmt.setDouble(3, bookedCred.getPrice()); //THN TIMH THS KRATHSHS
stmt.setInt(4, bookedCred.getPassengers()); //TON ARITHMO TWN EPIVATWN
//TREXOUME TO STATEMENT KAI APOTHYKEUOUME TIS EPIREASMENES GRAMMES
int rowsAffected = stmt.executeUpdate();
//ELEGXOUME AN EPHREASTHKE KAPOIA GRAMMH GIA NA DOUME AN EGINE H EISAGWGH
if (rowsAffected == 1) {
//PERNOUME TO ID THS PTHSHS
ResultSet generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next()) {
generatedId = generatedKeys.getInt(1);
}
}
return ("Η κράτηση έγινε επιτυχώς\nΚωδικός κράτησης : " + generatedId); //TO MINIMA AN EGINE H KRATHSH
} else {
return ("Δεν υπάρχουν διαθέσιμες θέσεις για τις πτήσεις."); //TO MHNIMA AN DEN YPIRXAN DIATHESIMES THESEIS
}
}
} catch (SQLException e) {
return ("Error inserting booking: " + e.getMessage()); //MINIMA AN PHGE KATI STRAVA KATA THN DIARKEIA THS EISAGWGHS STHN VASH
}
}
//METHODOS GIA NA PAIRNOUME TIS DIATHESIME PTHSEIS APO TON PINAKA TWN DIATHESIMWN PTHSEWN VASH ENOS ID PTHSHS
private int getAvailableSeats(int flightId) throws SQLException {
//DILWNOUME KAI ARXIKOPOIOUME TO SQL QUERY
String sql = "SELECT available_seats FROM available_flights WHERE flight_id = ?";
//DHMIOURGOUME TO PREPAREDSTATEMENT
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
//THETOUME THN TIMH GIA TO STATEMENT
stmt.setInt(1, flightId);
try (ResultSet rs = stmt.executeQuery()) { //TREXOUME TO STATEMENT
if (rs.next()) { //KAI AN VREI THN PTHSH
return rs.getInt("available_seats"); //EPISTREFOUME TON ARITHMO TWN DIATHESIMWN THESEWN
}
}
}
return 0; //ALLIWS EPISTREFOUME 0
}
//METHODOS GIA THN ANAZHTHSH DIATHESEWN THESEWN KAI DEXETAI WS ORISMA ENA ANTIKEIMENO POU PERIEXEI TIS MATAVLITES GIA THN ANAZHTHSH
public List<FlightBooking> searchData(FlightSearchCrit criteria) throws SQLException {
List<FlightBooking> availableFlights = new ArrayList<>(); //LISTA POU THA PERIEXEI OLES TIS DIATHESIMES PTHSEIS
List<Flight> departureFlights = new ArrayList<>(); //LISTA GIA TIS PTHSEIS POU ANAXWROUN
List<Flight> returnFlights = new ArrayList<>(); //LISTA GIA TIS PTHSEIS TWN AFHXEWN
//DILWNOUME KAI ARXIKOPOIOUME TO SQL QUERY TO OPOIO THA EINAI MONO GIA TIS MONES PTHSEIS H GIA TIS PTHSEIS TWN ANAXWRISEWN
String sql = "SELECT * FROM available_flights WHERE origin = ? AND destination = ? AND departure_date = ? AND available_seats >= ?";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //DILWNOUME ENA ANTIKEIMENO GIA NA FTIAXNEI TO FORMAT ETSI WSTE NA MPOROUME NA GINEI SWSTA H ANAZHTHSH KAI H APOTHYKEYSH
//DHMIOURGOUME TO PREPAREDSTATEMENT
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, criteria.getOrigin()); //THETOUME THN TIMH GIA THN TOPOTHESIA ANAXWRISIS
statement.setString(2, criteria.getDestination()); //THETOUME THN TIMH GIA THN TOPOTHESIA AFIXHS
statement.setString(3, criteria.getDepartureDate().toString()); //THETOUME THN TIMH GIA THN HMEROMHNIA ANAXWRISIS
statement.setInt(4, criteria.getPassengers()); //THETOUME THN TIMH GIA TON ARITHMO TWN EPIVATWN
//TREXOUME TO QUERY
ResultSet resultSet = statement.executeQuery();
//EPANALIPSH GIA OLA TA APOTELESMATA
while (resultSet.next()) {
//DILWSH METAVLITWN GIA THN KATAXWRHSH TWN APOTELESMATWN APO THN VASH
int departureFlightId = resultSet.getInt("flight_id"); //GIA TON KWDIKO THS PTHSHS ANAXWRHSHS
String origin = resultSet.getString("origin"); //H TOPOTHESIA ANAXWRHSHS
String destination = resultSet.getString("destination"); //H TOPOTHESIA PROORISMOU
String departureDateStr = resultSet.getString("departure_date"); //H HMEROMHNIA ANAXWRISHS
String departureTimeStr = resultSet.getString("departure_time"); //H WRA ANAXWRHSHS
String arrivalDateStr = resultSet.getString("arrival_date"); //H HMEROMHNIA AFIXHS
String arrivalTimeStr = resultSet.getString("arrival_time"); //H WRA AFIXHS
int availableSeats = resultSet.getInt("available_seats"); //GIA TIS DIATHESIMES THESEIS
double price = resultSet.getDouble("price"); //GIA THN TIMH
String originAirportId = resultSet.getString(8); //GIA TON KWDIKO AERODROMIOU ANAXWRHSHS
String destinationAirportId = resultSet.getString(9); //GIA TON KWDIKO AERODROMIOU AFIXHS
//DHMIOURGIA ANTIKEIMENOU LOCALDATETIME WSTE NA SYNDIASOUME TON XRONO KAI THN HMEROMHNIA SE MIA METAVLITH
String departureDateTimeStr = departureDateStr + " " + departureTimeStr; //FTIAXNOUME ENA STRING ME THN MERA ANAXWRHSHS KAI ME THN WRA
String arrivalDateTimeStr = arrivalDateStr + " " + arrivalTimeStr; //FTIAXNOUME ENA STRING ME THN MERA AFIXHS KAI ME THN WRA
LocalDateTime departureDateTime = LocalDateTime.parse(departureDateTimeStr, formatter); //DHMIOURGOUME TO ANTIKEIMENO GIA THN HMERA ANAXWRHSHS
LocalDateTime arrivalDateTime = LocalDateTime.parse(arrivalDateTimeStr, formatter); //DHMIOURGOUME TO ANTIKEIMENO GIA THN HMERA AFIXHS
//DHMIOURGOUME ANTIKEIMENO GIA THN PTHSH KAI TO ARXIKOPOIOUME ME TA APOTELESMATA
Flight departureFlight = new Flight(departureFlightId, origin, destination, departureDateTime, arrivalDateTime, availableSeats, price, originAirportId, destinationAirportId);
//EISAGOUME THN PTHSH STIS PTHSEIS ANAXWRHSEWN
departureFlights.add(departureFlight);
}
if (criteria.isIsRoundTrip()) {//AN H PTHSH EINAI ME EPISTROFH TOTE ANAZHTAEI KAI GIA TIS PTHSEIS POU YPARXOUN VASH TWN STOIXEIWN THS EPISTROFHS
//DHMIOURGIA KAI DILWSH TOU SQL QUERY
String returnSql = "SELECT * FROM available_flights WHERE origin = ? AND destination = ? AND departure_date = ? AND available_seats >= ?";
//DHMIOURGIA TOU PREPAREDSTATEMENT
PreparedStatement returnStatement = connection.prepareStatement(returnSql);
//THE TOUME TA STATEMENT
returnStatement.setString(1, criteria.getDestination()); //GIA THN TOPOTHESIA ANAXWRHSHS THS EPISTROFHS
returnStatement.setString(2, criteria.getOrigin()); //GIA THN TOPOTHESIA AFIXHS THS EPISTROFHS
returnStatement.setString(3, criteria.getReturnDate().toString()); //GIA THN HMERA ANAXWRHSHS THS EPISTROFHS
returnStatement.setInt(4, criteria.getPassengers()); //GIA TON ARXITHMO TWN EPIVATWN THS EPISTROFHS
//TREXOUME TO ERWTHMA KAI APOTHYKEUOUME TA RESULT
ResultSet returnResultSet = returnStatement.executeQuery();
//EPANALIPSI GIA OLA TA APOTELESMATA
while (returnResultSet.next()) {
//DILWSH METAVLITWN GIA THN KATAXWRHSH TWN APOTELESMATWN APO THN VASH
int returnFlightId = returnResultSet.getInt("flight_id"); //GIA TON KWDIKO THS PTHSHS EPISTROFHS
String returnOrigin = returnResultSet.getString("origin"); //GIA THN TOPOTHESIA ANAXWRHSHS THS EPISTROFHS
String returnDestination = returnResultSet.getString("destination"); //GIA THN TOPOTHESIA AFIXHS THS EPISTROFHS
String returnDepartureDateStr = returnResultSet.getString("departure_date"); //GIA THN HMERA ANAXWRHSHS THS EPISTROFHS
String returnDepartureTimeStr = returnResultSet.getString("departure_time"); //GIA THN WRA ANAXWRHSHS THS EPISTROFHS
String returnArrivalDateStr = returnResultSet.getString("arrival_date"); //GIA THN HMERA AFIXHS THS EPISTROFHS
String returnArrivalTimeStr = returnResultSet.getString("arrival_time"); //GIA THN WRA AFIXHS THS EPISTROFHS
int returnAvailableSeats = returnResultSet.getInt("available_seats"); //GIA TIS DIATHESIMES THESEIS THS EPISTROFHS
double returnPrice = returnResultSet.getDouble("price"); //GIA THN TIMH THS EPISTROFHS
String returnOriginAirportId = returnResultSet.getString(8); //GIA TON KWDIKO AERODROMIOU ANAXWRHSHS THS EPISTROFHS
String returnDestinationAirportId = returnResultSet.getString(9); //GIA TON KWDIKO AERODROMIOU AFIXHS THS EPISTROFHS
//DHMIOURGIA ANTIKEIMENOU LOCALDATETIME WSTE NA SYNDIASOUME TON XRONO KAI THN HMEROMHNIA SE MIA METAVLITH
String returnDepartureDateTimeStr = returnDepartureDateStr + " " + returnDepartureTimeStr; //FTIAXNOUME ENA STRING ME THN MERA ANAXWRHSHS KAI ME THN WRA
String returnArrivalDateTimeStr = returnArrivalDateStr + " " + returnArrivalTimeStr; //FTIAXNOUME ENA STRING ME THN MERA AFIXHS KAI ME THN WRA
LocalDateTime returnDepartureDateTime = LocalDateTime.parse(returnDepartureDateTimeStr, formatter); //DHMIOURGOUME TO ANTIKEIMENO GIA THN HMERA ANAXWRHSHS
LocalDateTime returnArrivalDateTime = LocalDateTime.parse(returnArrivalDateTimeStr, formatter); //DHMIOURGOUME TO ANTIKEIMENO GIA THN HMERA AFIXHS
//DHMIOURGOUME ANTIKEIMENO GIA THN PTHSH KAI TO ARXIKOPOIOUME ME TA APOTELESMATA
Flight returnFlight = new Flight(returnFlightId, returnOrigin, returnDestination, returnDepartureDateTime, returnArrivalDateTime, returnAvailableSeats, returnPrice, returnOriginAirportId, returnDestinationAirportId);
//EISAGOUME THN PTHSH STIS PTHSEIS EPISTROFWN
returnFlights.add(returnFlight);
}
//DIATREXOUME TIS LISTES TWN ANAXWRHSEWN KAI TWN EPISTROFWN WSTE NA APOTHYKEUSOUME OLOUS TOU SYNDIASMOUS STIS DIATHESIMES PTHSEIS
for (Flight outboundFlight : departureFlights) { //EPANALIPSI GIA OLES TIS PTHSEIS TWN ANAXWRHSEWN
for (Flight returnFlight : returnFlights) { //EPANALIPSI GIA OLES TIS PTHSEIS TWN EPISTROFWN
//ELEGXOUME AN H WRA THS AFIXHS THS PTHSHS ANAXWRHSHS EINAI PIO PRIN TOULAXISTON 15 LEPTA APO THN WRA ANAXWRHSHS THS EPISTROFHS KAI TOTE FTIAXNOUME THN PTHSH KAI THN EISAGOUME STHNLISTA
if(returnFlight.getDepartureDate().toLocalTime().isAfter(outboundFlight.getArrivalDate().toLocalTime().plusMinutes(15))){
availableFlights.add(new FlightBooking(outboundFlight,returnFlight,criteria.getPassengers()));
}
}
}
}
else{ //ALLIWS AN EINAI MONH PTHSH
for(Flight i:departureFlights){ //KANH EPANALHPSH GIA OLES TIS PTHSEIS
availableFlights.add(new FlightBooking(i,criteria.getPassengers())); //EISAGEI MIA NEA PTHSH ME MONO THN MONH PTHSH KAI TOUS EPIVATES KAI THN EISAGEI STIS DIATHESIMES
}
}
return availableFlights;//EPISTREFEI TIS DIATHESIMES PTHSEIS
}
//METHODOS GIA THN ANAZHTHSH STHN VASH GIA TIS POLEIS TWN PTHSEWN
public String[] searchData() throws SQLException {
//DILWSH KAI ARXIKOPOIHSH TOU SQL QUERY
String sql = "SELECT DISTINCT location FROM airports";
String[] locations; //DILWSH ENOS PINAKA STRING GIA TIS TOPOTHESIES
StringBuilder strB = new StringBuilder(); //DILWSH ENOS STRINGBUILDER GIA NA PROSTHETEI TIS TOPOTHESIES
//DIMIOURGEIA TOU PREPARED STATEMENT
try (Statement statement = connection.createStatement();
//TREXIMO TOU STATEMENT
ResultSet resultSet = statement.executeQuery(sql)) {
//EPEXERGASIA TWN APOTELESMATWN
while (resultSet.next()) {
//PERNOUME THN TOPOTHESIA KAI THN EISAGOUME STHN STRINGBUILDER METAVLITH ME ,
strB.append(resultSet.getString("location")).append(",");
}
String str = strB.toString(); //METATREPOUME TON STRINGBUILDER SE STRING
locations = str.split(","); //APOTHYKEUOUME TIS POLEIS DIAXWRIZONTAS ME , STON PINAKA
Arrays.sort(locations); //SORTAROUME TON PINAKA KATA AUXOUSA SEIRA
}
return(locations); //EPISTREFOUME TWN PINAKA POU EXEI TIS POLEIS
}
} | DionysisTheodosis/Java-Exercises | Κατανεμημένα/DSPROGECT02icsd15066/Server2/src/server2/DatabaseManager.java |
45,711 |
public class Mathematics {
// Σταθερά
public static final double PI = 3.14;
public static int cube(int x) {
return (x*x*x);
}
}
| madskgg/UoM-Applied-Informatics | Semester3/Object-Oriented Programming/Lectures/Week05/Game/Mathematics.java |
45,848 | package android.util;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Patterns {
public static final Pattern AUTOLINK_EMAIL_ADDRESS = Pattern.compile("((?:\\b|$|^)(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'\\.]{1,62}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'])?@(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63}))(?:\\b|$|^))");
public static final Pattern AUTOLINK_WEB_URL = Pattern.compile("(((?:\\b|$|^)(?:(?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))|((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^)))");
public static final Pattern AUTOLINK_WEB_URL_EMUI = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:" + DOMAIN_NAME_EMUI + ")" + "(?:\\:\\d{1,5})?)" + "((?:\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~" + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))+[\\;\\.\\=\\?\\/\\+\\)][a-zA-Z0-9\\%\\#\\&\\-\\_\\.\\~]*)" + "|(?:\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~" + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*))?" + "(?:\\b|$|(?=[ -豈-﷏ﷰ-]))", 2);
public static final Pattern DOMAIN_NAME = Pattern.compile(DOMAIN_NAME_STR);
public static final Pattern DOMAIN_NAME_EMUI = Pattern.compile("(([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}\\.)+[a-zA-Z]{2,63}|" + IP_ADDRESS + ")");
private static final String DOMAIN_NAME_STR = "(([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
public static final Pattern EMAIL_ADDRESS = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+");
private static final String EMAIL_ADDRESS_DOMAIN = "(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String EMAIL_ADDRESS_LOCAL_PART = "[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'\\.]{1,62}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'])?";
private static final String EMAIL_CHAR = "a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'";
private static final String GOOD_GTLD_CHAR_EMUI = "a-zA-Z";
@Deprecated
public static final String GOOD_IRI_CHAR = "a-zA-Z0-9 -豈-﷏ﷰ-";
public static final String GOOD_IRI_CHAR_EMUI = "a-zA-Z0-9";
private static final String GTLD_EMUI = "[a-zA-Z]{2,63}";
private static final String HOST_NAME = "([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String HOST_NAME_EMUI = "([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}\\.)+[a-zA-Z]{2,63}";
static final String IANA_TOP_LEVEL_DOMAINS = "(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))";
public static final Pattern IP_ADDRESS = Pattern.compile(IP_ADDRESS_STRING);
private static final String IP_ADDRESS_STRING = "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))";
private static final String IRI_EMUI = "[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}";
private static final String IRI_LABEL = "[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}";
private static final String LABEL_CHAR = "a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
private static final String PATH_AND_QUERY = "[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*";
public static final Pattern PHONE = Pattern.compile("(\\+[0-9]+[\\- \\.]*)?(\\([0-9]+\\)[\\- \\.]*)?([0-9][0-9\\- \\.]+[0-9])");
private static final String PORT_NUMBER = "\\:\\d{1,5}";
private static final String PROTOCOL = "(?i:http|https|rtsp)://";
private static final String PUNYCODE_TLD = "xn\\-\\-[\\w\\-]{0,58}\\w";
private static final String RELAXED_DOMAIN_NAME = "(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
private static final String STRICT_DOMAIN_NAME = "(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
private static final String STRICT_HOST_NAME = "(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))";
private static final String STRICT_TLD = "(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w)";
private static final String TLD = "(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String TLD_CHAR = "a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
@Deprecated
public static final Pattern TOP_LEVEL_DOMAIN = Pattern.compile(TOP_LEVEL_DOMAIN_STR);
@Deprecated
public static final String TOP_LEVEL_DOMAIN_STR = "((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw])";
@Deprecated
public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL = "(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))";
private static final String UCS_CHAR = "[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
private static final String USER_INFO = "(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@";
public static final Pattern WEB_URL = Pattern.compile("(((?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)([/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))");
private static final String WEB_URL_WITHOUT_PROTOCOL = "((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))";
private static final String WEB_URL_WITH_PROTOCOL = "((?:\\b|$|^)(?:(?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))";
private static final String WORD_BOUNDARY = "(?:\\b|$|^)";
public static final String concatGroups(Matcher matcher) {
StringBuilder b = new StringBuilder();
int numGroups = matcher.groupCount();
for (int i = 1; i <= numGroups; i++) {
String s = matcher.group(i);
if (s != null) {
b.append(s);
}
}
return b.toString();
}
public static final String digitsAndPlusOnly(Matcher matcher) {
StringBuilder buffer = new StringBuilder();
String matchingRegion = matcher.group();
int size = matchingRegion.length();
for (int i = 0; i < size; i++) {
char character = matchingRegion.charAt(i);
if (character == '+' || Character.isDigit(character)) {
buffer.append(character);
}
}
return buffer.toString();
}
private Patterns() {
}
public static Pattern getWebUrl() {
if (Locale.CHINESE.getLanguage().equals(Locale.getDefault().getLanguage())) {
return AUTOLINK_WEB_URL_EMUI;
}
return AUTOLINK_WEB_URL;
}
}
| dstmath/HWFramework | P9-8.0/src/main/java/android/util/Patterns.java |
45,850 | import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class arcu
{
public static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?((?:(?:[a-zA-Z0-9 -豈-﷏ﷰ-][a-zA-Z0-9 -豈-﷏ﷰ-\\-]{0,64}\\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9 -豈-﷏ﷰ-\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?(?:\\b|$)");
public static boolean isUrl(String paramString)
{
if (paramString == null) {
return false;
}
return WEB_URL.matcher(paramString).find();
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.tim\classes4.jar
* Qualified Name: arcu
* JD-Core Version: 0.7.0.1
*/ | tsuzcx/qq_apk | com.tencent.tim/classes.jar/arcu.java |
45,854 | package android.util;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Patterns {
public static final Pattern AUTOLINK_EMAIL_ADDRESS = Pattern.compile("((?:\\b|$|^)(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'\\.]{0,62}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'])?@(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63}))(?:\\b|$|^))");
public static final Pattern AUTOLINK_WEB_URL = Pattern.compile("(((?:\\b|$|^)(?:(?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))|((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^)))");
public static final Pattern AUTOLINK_WEB_URL_EMUI;
public static final Pattern DOMAIN_NAME = Pattern.compile(DOMAIN_NAME_STR);
public static final Pattern DOMAIN_NAME_EMUI;
private static final String DOMAIN_NAME_STR = "(([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
public static final Pattern EMAIL_ADDRESS = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+");
private static final String EMAIL_ADDRESS_DOMAIN = "(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String EMAIL_ADDRESS_LOCAL_PART = "[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'\\.]{0,62}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'])?";
private static final String EMAIL_CHAR = "a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'";
private static final String GOOD_GTLD_CHAR_EMUI = "a-zA-Z";
@Deprecated
public static final String GOOD_IRI_CHAR = "a-zA-Z0-9 -豈-﷏ﷰ-";
public static final String GOOD_IRI_CHAR_EMUI = "a-zA-Z0-9";
private static final String GTLD_EMUI = "[a-zA-Z]{2,63}";
private static final String HOST_NAME = "([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String HOST_NAME_EMUI = "([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}\\.)+[a-zA-Z]{2,63}";
static final String IANA_TOP_LEVEL_DOMAINS = "(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))";
public static final Pattern IP_ADDRESS = Pattern.compile(IP_ADDRESS_STRING);
private static final String IP_ADDRESS_STRING = "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))";
private static final String IRI_EMUI = "[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}";
private static final String IRI_LABEL = "[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}";
private static final String LABEL_CHAR = "a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
private static final String PATH_AND_QUERY = "[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*";
public static final Pattern PHONE = Pattern.compile("(\\+[0-9]+[\\- \\.]*)?(\\([0-9]+\\)[\\- \\.]*)?([0-9][0-9\\- \\.]+[0-9])");
private static final String PORT_NUMBER = "\\:\\d{1,5}";
private static final String PROTOCOL = "(?i:http|https|rtsp)://";
private static final String PUNYCODE_TLD = "xn\\-\\-[\\w\\-]{0,58}\\w";
private static final String RELAXED_DOMAIN_NAME = "(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
private static final String STRICT_DOMAIN_NAME = "(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
private static final String STRICT_HOST_NAME = "(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))";
private static final String STRICT_TLD = "(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w)";
private static final String TLD = "(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String TLD_CHAR = "a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
@Deprecated
public static final Pattern TOP_LEVEL_DOMAIN = Pattern.compile(TOP_LEVEL_DOMAIN_STR);
@Deprecated
public static final String TOP_LEVEL_DOMAIN_STR = "((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw])";
@Deprecated
public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL = "(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))";
private static final String UCS_CHAR = "[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
private static final String USER_INFO = "(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@";
public static final Pattern WEB_URL = Pattern.compile("(((?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)([/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))");
private static final String WEB_URL_WITHOUT_PROTOCOL = "((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))";
private static final String WEB_URL_WITH_PROTOCOL = "((?:\\b|$|^)(?:(?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))";
private static final String WORD_BOUNDARY = "(?:\\b|$|^)";
static {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("(([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}\\.)+[a-zA-Z]{2,63}|");
stringBuilder.append(IP_ADDRESS);
stringBuilder.append(")");
DOMAIN_NAME_EMUI = Pattern.compile(stringBuilder.toString());
stringBuilder = new StringBuilder();
stringBuilder.append("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:");
stringBuilder.append(DOMAIN_NAME_EMUI);
stringBuilder.append(")(?:\\:\\d{1,5})?)((?:\\/(?:(?:[");
stringBuilder.append(GOOD_IRI_CHAR);
stringBuilder.append("\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))+[\\;\\.\\=\\?\\/\\+\\)][a-zA-Z0-9\\%\\#\\&\\-\\_\\.\\~]*)|(?:\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*))?(?:\\b|$|(?=[ -豈-﷏ﷰ-]))");
AUTOLINK_WEB_URL_EMUI = Pattern.compile(stringBuilder.toString(), 2);
}
public static final String concatGroups(Matcher matcher) {
StringBuilder b = new StringBuilder();
int numGroups = matcher.groupCount();
for (int i = 1; i <= numGroups; i++) {
String s = matcher.group(i);
if (s != null) {
b.append(s);
}
}
return b.toString();
}
public static final String digitsAndPlusOnly(Matcher matcher) {
StringBuilder buffer = new StringBuilder();
String matchingRegion = matcher.group();
int size = matchingRegion.length();
for (int i = 0; i < size; i++) {
char character = matchingRegion.charAt(i);
if (character == '+' || Character.isDigit(character)) {
buffer.append(character);
}
}
return buffer.toString();
}
private Patterns() {
}
public static Pattern getWebUrl() {
if (Locale.CHINESE.getLanguage().equals(Locale.getDefault().getLanguage())) {
return AUTOLINK_WEB_URL_EMUI;
}
return AUTOLINK_WEB_URL;
}
}
| SivanLiu/HwFrameWorkSource | Mate20_9_0_0/src/main/java/android/util/Patterns.java |
45,855 | package gr.aueb.dmst.dirtybits;
import java.util.Scanner;
public class SplitTest {
public static void main (String[] args) {
String text1 = "Γεια σας παιδιά!";
String text2 = "δοκιμή με κενό";
String text3 = "στα 5 χρόνια";
String text4 = "Καλημέρα +++ καληνύχτα";
String[] words1 = text1.split("[^a-zA-Zα-ωΑ-Ωά-ώΐ]+");
String[] words2 = text2.split("[^a-zA-Zα-ωΑ-Ωά-ώΐ]+");
String[] words3 = text3.split("[^a-zA-Zα-ωΑ-Ωά-ώΐ]+");
String[] words4 = text4.split("[^a-zA-Zα-ωΑ-Ωά-ώΐ]+");
String[] array1 = words1;
String[] array2 = words2;
String[] array3 = words3;
String[] array4 = words4;
if (array1[0].equals("Γεια")) {
System.out.println("try 1:");
System.out.println("well done team!");
System.out.println("H methodos splitArray douleuei kanonika");
} else {
System.out.println("try again");
System.out.println(array1[0]);
}
for (int i=0 ; i< array1.length;i ++) {
if(array1[i] != null) {
System.out.println();
System.out.println(array1[i]);
System.out.println("\n");
}
}
if (array2[2].equals("κενό")) {
System.out.println("try 2:");
System.out.println("well done team!");
System.out.println("To programma douleuei osa kena kai na exei anamesa stis le3eis");
} else {
System.out.println("try again");
System.out.println(array2[2]);
}
for (int i=0 ; i< array2.length;i ++) {
if(array2[i] != null) {
System.out.println();
System.out.println(array2[i]);
System.out.println("\n");
}
}
if (array3[1].equals("χρόνια")) {
System.out.println("try 3:");
System.out.println("well done team!");
System.out.println("To programma douleuei kai me arithmous anamesa apo tis le3eis");
} else {
System.out.println("try again");
System.out.println(array3[1]);
}
for (int i=0 ; i< array3.length;i ++) {
if(array3[i] != null) {
System.out.println();
System.out.println(array3[i]);
System.out.println("\n");
}
}
if (array4[1].equals("καληνύχτα")) {
System.out.println("try 4:");
System.out.println("well done team!");
System.out.println("To programma douleuei kai me symvola anamesa apo tis le3eis");
} else {
System.out.println("try again");
System.out.println(array4[1]);
}
for (int i=0 ; i< array4.length;i ++) {
if(array4[i] != null) {
System.out.println();
System.out.println(array4[i]);
System.out.println("\n");
}
}
}
}
| kbabetas/Spellchecker | src/tests/java/gr/aueb/dmst/dirtybits/SplitTest.java |
45,856 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.codec.socks;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class SocksAuthRequestTest {
@Test
public void testConstructorParamsAreNotNull() {
try {
new SocksAuthRequest(null, "");
} catch (Exception e) {
assertTrue(e instanceof NullPointerException);
}
try {
new SocksAuthRequest("", null);
} catch (Exception e) {
assertTrue(e instanceof NullPointerException);
}
}
@Test
public void testUsernameOrPasswordIsNotAscii() {
try {
new SocksAuthRequest("παράδειγμα.δοκιμή", "password");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
new SocksAuthRequest("username", "παράδειγμα.δοκιμή");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testUsernameOrPasswordLengthIsLessThan255Chars() {
try {
new SocksAuthRequest(
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword",
"password");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
new SocksAuthRequest("password",
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
}
| mheath/netty | codec-socks/src/test/java/io/netty/codec/socks/SocksAuthRequestTest.java |
45,857 | /****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package org.apache.james.core;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import java.util.stream.Stream;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import nl.jqno.equalsverifier.EqualsVerifier;
class MailAddressTest {
private static final String GOOD_LOCAL_PART = "\"quoted@local part\"";
private static final String GOOD_QUOTED_LOCAL_PART = "\"quoted@local part\"@james.apache.org";
private static final String GOOD_ADDRESS = "[email protected]";
private static final Domain GOOD_DOMAIN = Domain.of("james.apache.org");
private static Stream<Arguments> goodAddresses() {
return Stream.of(
GOOD_ADDRESS,
GOOD_QUOTED_LOCAL_PART,
"[email protected]",
"server-dev@[127.0.0.1]",
"[email protected]",
"\\[email protected]",
"[email protected]",
"[email protected]",
"user+mailbox/[email protected]",
"\"Abc@def\"@example.com",
"\"Fred Bloggs\"@example.com",
"\"Joe.\\Blow\"@example.com",
"!#$%&'*+-/=?^_`.{|}[email protected]")
.map(Arguments::of);
}
private static Stream<Arguments> badAddresses() {
return Stream.of(
"",
"server-dev",
"server-dev@",
"[]",
"server-dev@[]",
"server-dev@#",
"quoted [email protected]",
"quoted@[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected].",
"[email protected]",
"[email protected]",
"[email protected]",
"server-dev@#james.apache.org",
"server-dev@#123james.apache.org",
"server-dev@#-123.james.apache.org",
"server-dev@james. apache.org",
"server-dev@james\\.apache.org",
"server-dev@[300.0.0.1]",
"server-dev@[127.0.1]",
"server-dev@[0127.0.0.1]",
"server-dev@[127.0.1.1a]",
"server-dev@[127\\.0.1.1]",
"server-dev@#123",
"server-dev@#123.apache.org",
"server-dev@[127.0.1.1.1]",
"server-dev@[127.0.1.-1]",
"\"a..b\"@domain.com", // Javax.mail is unable to handle this so we better reject it
"server-dev\\[email protected]", // Javax.mail is unable to handle this so we better reject it
"[email protected]",
// According to wikipedia these addresses are valid but as javax.mail is unable
// to work with thenm we shall rather reject them (note that this is not breaking retro-compatibility)
"Loïc.Accentué@voilà.fr8",
"pelé@exemple.com",
"δοκιμή@παράδειγμα.δοκιμή",
"我買@屋企.香港",
"二ノ宮@黒川.日本",
"медведь@с-балалайкой.рф",
"संपर्क@डाटामेल.भारत")
.map(Arguments::of);
}
@ParameterizedTest
@MethodSource("goodAddresses")
void testGoodMailAddressString(String mailAddress) {
assertThatCode(() -> new MailAddress(mailAddress))
.doesNotThrowAnyException();
}
@ParameterizedTest
@MethodSource("goodAddresses")
void toInternetAddressShouldNoop(String mailAddress) throws Exception {
assertThat(new MailAddress(mailAddress).toInternetAddress())
.isNotEmpty();
}
@ParameterizedTest
@MethodSource("badAddresses")
void testBadMailAddressString(String mailAddress) {
Assertions.assertThatThrownBy(() -> new MailAddress(mailAddress))
.isInstanceOf(AddressException.class);
}
@Test
void testGoodMailAddressWithLocalPartAndDomain() {
assertThatCode(() -> new MailAddress("local-part", "domain"))
.doesNotThrowAnyException();
}
@Test
void testBadMailAddressWithLocalPartAndDomain() {
Assertions.assertThatThrownBy(() -> new MailAddress("local-part", "-domain"))
.isInstanceOf(AddressException.class);
}
@Test
void testMailAddressInternetAddress() {
assertThatCode(() -> new MailAddress(new InternetAddress(GOOD_QUOTED_LOCAL_PART)))
.doesNotThrowAnyException();
}
@Test
void testGetDomain() throws AddressException {
MailAddress a = new MailAddress(new InternetAddress(GOOD_ADDRESS));
assertThat(a.getDomain()).isEqualTo(GOOD_DOMAIN);
}
@Test
void testGetLocalPart() throws AddressException {
MailAddress a = new MailAddress(new InternetAddress(GOOD_QUOTED_LOCAL_PART));
assertThat(a.getLocalPart()).isEqualTo(GOOD_LOCAL_PART);
}
@Test
void testToString() throws AddressException {
MailAddress a = new MailAddress(new InternetAddress(GOOD_ADDRESS));
assertThat(a.toString()).isEqualTo(GOOD_ADDRESS);
}
@Test
void testToInternetAddress() throws AddressException {
InternetAddress b = new InternetAddress(GOOD_ADDRESS);
MailAddress a = new MailAddress(b);
assertThat(a.toInternetAddress()).contains(b);
assertThat(a.toString()).isEqualTo(GOOD_ADDRESS);
}
@Test
void testEqualsObject() throws AddressException {
MailAddress a = new MailAddress(GOOD_ADDRESS);
MailAddress b = new MailAddress(GOOD_ADDRESS);
assertThat(a).isNotNull().isEqualTo(b);
}
@Test
void equalsShouldReturnTrueWhenBothNullSender() {
assertThat(MailAddress.nullSender())
.isEqualTo(MailAddress.nullSender());
}
@SuppressWarnings("deprecation")
@Test
void getMailSenderShouldReturnNullSenderWhenNullSender() {
assertThat(MailAddress.getMailSender(MailAddress.NULL_SENDER_AS_STRING))
.isEqualTo(MailAddress.nullSender());
}
@SuppressWarnings("deprecation")
@Test
void getMailSenderShouldReturnParsedAddressWhenNotNullAddress() throws Exception {
assertThat(MailAddress.getMailSender(GOOD_ADDRESS))
.isEqualTo(new MailAddress(GOOD_ADDRESS));
}
@SuppressWarnings("deprecation")
@Test
void equalsShouldReturnFalseWhenOnlyFirstMemberIsANullSender() {
assertThat(MailAddress.getMailSender(GOOD_ADDRESS))
.isNotEqualTo(MailAddress.nullSender());
}
@SuppressWarnings("deprecation")
@Test
void equalsShouldReturnFalseWhenOnlySecondMemberIsANullSender() {
assertThat(MailAddress.nullSender())
.isNotEqualTo(MailAddress.getMailSender(GOOD_ADDRESS));
}
@Test
void shouldMatchBeanContract() {
EqualsVerifier.forClass(MailAddress.class)
.verify();
}
}
| amichair/james-project | core/src/test/java/org/apache/james/core/MailAddressTest.java |
45,858 | package com.lenovo.anyshare;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* loaded from: classes7.dex */
public class _Mf {
@Deprecated
/* renamed from: a reason: collision with root package name */
public static final Pattern f17945a = Pattern.compile("((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw])");
public static final Pattern b = Pattern.compile("((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))");
public static final Pattern c = Pattern.compile("(([a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))");
public static final Pattern d = Pattern.compile("(((?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(([a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)([/\\?](?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))");
public static final Pattern e = Pattern.compile("(((?:\\b|$|^)(?:(?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))|((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^)))");
public static final Pattern f = Pattern.compile("((?:\\b|$|^)(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]\\+\\-_%'](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]\\+\\-_%'\\.]{0,62}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]\\+\\-_%'])?@(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd𰀀-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]{2,63}))(?:\\b|$|^))");
public static final Pattern g = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+");
public static final Pattern h = Pattern.compile("(\\+[0-9]+[\\- \\.]*)?(\\([0-9]+\\)[\\- \\.]*)?([0-9][0-9\\- \\.]+[0-9])");
public static final String a(Matcher matcher) {
StringBuilder sb = new StringBuilder();
int groupCount = matcher.groupCount();
for (int i = 1; i <= groupCount; i++) {
String group = matcher.group(i);
if (group != null) {
sb.append(group);
}
}
return sb.toString();
}
public static final String b(Matcher matcher) {
StringBuilder sb = new StringBuilder();
String group = matcher.group();
int length = group.length();
for (int i = 0; i < length; i++) {
char charAt = group.charAt(i);
if (charAt == '+' || Character.isDigit(charAt)) {
sb.append(charAt);
}
}
return sb.toString();
}
}
| meltingscales/com.lenovo.anyshare.gps | jadx/sources/com/lenovo/anyshare/_Mf.java |
45,859 | package com.boli.core.wallet;
import com.boli.core.coins.BitcoinMain;
import com.boli.core.coins.CoinType;
import com.boli.core.coins.DogecoinTest;
import com.boli.core.coins.NuBitsMain;
import com.boli.core.coins.Value;
import com.boli.core.coins.VpncoinMain;
import com.boli.core.exceptions.AddressMalformedException;
import com.boli.core.exceptions.Bip44KeyLookAheadExceededException;
import com.boli.core.exceptions.KeyIsEncryptedException;
import com.boli.core.exceptions.MissingPrivateKeyException;
import com.boli.core.network.AddressStatus;
import com.boli.core.network.BlockHeader;
import com.boli.core.network.ServerClient.HistoryTx;
import com.boli.core.network.ServerClient.UnspentTx;
import com.boli.core.network.interfaces.ConnectionEventListener;
import com.boli.core.network.interfaces.TransactionEventListener;
import com.boli.core.protos.Protos;
import com.boli.core.wallet.families.bitcoin.BitAddress;
import com.boli.core.wallet.families.bitcoin.BitBlockchainConnection;
import com.boli.core.wallet.families.bitcoin.BitSendRequest;
import com.boli.core.wallet.families.bitcoin.BitTransaction;
import com.boli.core.wallet.families.bitcoin.BitTransactionEventListener;
import com.boli.core.wallet.families.bitcoin.OutPointOutput;
import com.boli.core.wallet.families.bitcoin.TrimmedOutPoint;
import com.google.common.collect.ImmutableList;
import org.bitcoinj.core.ChildMessage;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence.Source;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.core.Utils;
import org.bitcoinj.crypto.DeterministicHierarchy;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.crypto.KeyCrypter;
import org.bitcoinj.crypto.KeyCrypterScrypt;
import org.bitcoinj.store.UnreadableWalletException;
import org.bitcoinj.utils.BriefLogFormatter;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bitcoinj.wallet.KeyChain;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.spongycastle.crypto.params.KeyParameter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.boli.core.Preconditions.checkNotNull;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author John L. Jegutanis
*/
public class WalletPocketHDTest {
static final CoinType BTC = BitcoinMain.get();
static final CoinType DOGE = DogecoinTest.get();
static final CoinType NBT = NuBitsMain.get();
static final CoinType VPN = VpncoinMain.get();
static final List<String> MNEMONIC = ImmutableList.of("citizen", "fever", "scale", "nurse", "brief", "round", "ski", "fiction", "car", "fitness", "pluck", "act");
static final byte[] AES_KEY_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7};
static final long AMOUNT_TO_SEND = 2700000000L;
static final String MESSAGE = "test";
static final String MESSAGE_UNICODE = "δοκιμή испытание 测试";
static final String EXPECTED_BITCOIN_SIG = "IMBbIFDDuUwomYlvSjwWytqP/CXYym2yOKbJUx8Y+ujzZKBwoCFMr73GUxpr1Ird/DvnNZcsQLphvx18ftqN54o=";
static final String EXPECTED_BITCOIN_SIG_UNICODE = "IGGZEOBsVny5dozTOfc2/3UuvmZGdDI4XK/03HIk34PILd2oXbnq+87GINT3lumeXcgSO2NkGzUFcQ1SCSVI3Hk=";
static final String EXPECTED_NUBITS_SIG = "IMuzNZTZIjZjLicyDFGzqFl21vqNBGW1N5m4qHBRqbTvLBbkQeGjraeLmZEt7mRH4MSMPLFXW2T3Maz+HYx1tEc=";
static final String EXPECTED_NUBITS_SIG_UNICODE = "Hx7xkBbboXrp96dbQrJFzm2unTGwLstjbWlKa1/N1E4LJqbwJAJR1qIvwXm6LHQFnLOzwoQA45zYNjwUEPMc8sg=";
DeterministicSeed seed = new DeterministicSeed(MNEMONIC, null, "", 0);
DeterministicKey masterKey = HDKeyDerivation.createMasterPrivateKey(checkNotNull(seed.getSeedBytes()));
DeterministicHierarchy hierarchy = new DeterministicHierarchy(masterKey);
DeterministicKey rootKey = hierarchy.get(DOGE.getBip44Path(0), false, true);
KeyParameter aesKey = new KeyParameter(AES_KEY_BYTES);
KeyCrypter crypter = new KeyCrypterScrypt();
WalletPocketHD pocket;
@Before
public void setup() {
BriefLogFormatter.init();
pocket = new WalletPocketHD(rootKey, DOGE, null, null);
pocket.keys.setLookaheadSize(20);
}
@Test
public void testId() throws Exception {
assertEquals("8747886e9a77fe2a1588df3168b867648434d6d339b0b448793ae1db8f283f41", pocket.getId());
}
@Test
public void testSingleAddressWallet() throws Exception {
ECKey key = pocket.keys.getCurrentUnusedKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
BitWalletSingleKey bitWalletSingleKey = new BitWalletSingleKey(DOGE, key);
bitWalletSingleKey.onConnection(getBlockchainConnection(DOGE));
assertEquals(DOGE.value("10"), bitWalletSingleKey.getBalance());
}
@Test
public void xpubWallet() {
String xpub = "xpub67tVq9TLPPoaHVSiYu8mqahm3eztTPUts6JUftNq3pZF1PJwjknrTqQhjc2qRGd6vS8wANu7mLnqkiUzFZ1xZsAZoUMi8o6icMhzGCAhcSW";
DeterministicKey key = DeterministicKey.deserializeB58(null, xpub);
WalletPocketHD account = new WalletPocketHD(key, BTC, null, null);
assertEquals("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", account.getReceiveAddress().toString());
account = new WalletPocketHD(key, NBT, null, null);
assertEquals("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", account.getReceiveAddress().toString());
}
@Test
public void xpubWalletSerialized() throws Exception {
WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null);
Protos.WalletPocket proto = account.toProtobuf();
WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null);
assertEquals(account.getPublicKeySerialized(), newAccount.getPublicKeySerialized());
}
@Test
public void signMessage() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException {
WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature());
signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature());
pocketHD = new WalletPocketHD(rootKey, NBT, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_NUBITS_SIG, signedMessage.getSignature());
signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE_UNICODE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_NUBITS_SIG_UNICODE, signedMessage.getSignature());
}
@Test
public void signMessageEncrypted() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException {
WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
pocketHD.encrypt(crypter, aesKey);
SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE);
pocketHD.signMessage(signedMessage, aesKey);
assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature());
signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE);
pocketHD.signMessage(signedMessage, aesKey);
assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature());
}
@Test
public void signMessageEncryptedFailed() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException {
WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
pocketHD.encrypt(crypter, aesKey);
SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE);
pocketHD.signMessage(signedMessage, null);
assertEquals(SignedMessage.Status.KeyIsEncrypted, signedMessage.status);
}
@Test
public void watchingAddresses() {
List<AbstractAddress> watchingAddresses = pocket.getAddressesToWatch();
assertEquals(40, watchingAddresses.size()); // 20 + 20 lookahead size
for (int i = 0; i < addresses.size(); i++) {
assertEquals(addresses.get(i), watchingAddresses.get(i).toString());
}
}
@Test
public void issuedKeys() throws Bip44KeyLookAheadExceededException {
List<BitAddress> issuedAddresses = new ArrayList<>();
assertEquals(0, pocket.getIssuedReceiveAddresses().size());
assertEquals(0, pocket.keys.getNumIssuedExternalKeys());
issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
BitAddress freshAddress = pocket.getFreshReceiveAddress();
assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
assertEquals(1, pocket.getIssuedReceiveAddresses().size());
assertEquals(1, pocket.keys.getNumIssuedExternalKeys());
assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses());
issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
freshAddress = pocket.getFreshReceiveAddress();
assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
assertEquals(2, pocket.getIssuedReceiveAddresses().size());
assertEquals(2, pocket.keys.getNumIssuedExternalKeys());
assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses());
}
@Test
public void issuedKeysLimit() throws Exception {
assertTrue(pocket.canCreateFreshReceiveAddress());
try {
for (int i = 0; i < 100; i++) {
pocket.getFreshReceiveAddress();
}
} catch (Bip44KeyLookAheadExceededException e) {
assertFalse(pocket.canCreateFreshReceiveAddress());
// We haven't used any key so the total must be 20 - 1 (the unused key)
assertEquals(19, pocket.getNumberIssuedReceiveAddresses());
assertEquals(19, pocket.getIssuedReceiveAddresses().size());
}
pocket.onConnection(getBlockchainConnection(DOGE));
assertTrue(pocket.canCreateFreshReceiveAddress());
try {
for (int i = 0; i < 100; i++) {
pocket.getFreshReceiveAddress();
}
} catch (Bip44KeyLookAheadExceededException e) {
// try {
// pocket.getFreshReceiveAddress();
// } catch (Bip44KeyLookAheadExceededException e1) { /* ignore */ }
assertFalse(pocket.canCreateFreshReceiveAddress());
// We used 18, so the total must be (20-1)+18=37
assertEquals(37, pocket.getNumberIssuedReceiveAddresses());
assertEquals(37, pocket.getIssuedReceiveAddresses().size());
}
}
@Test
public void issuedKeysLimit2() throws Exception {
assertTrue(pocket.canCreateFreshReceiveAddress());
try {
for (int i = 0; i < 100; i++) {
pocket.getFreshReceiveAddress();
}
} catch (Bip44KeyLookAheadExceededException e) {
assertFalse(pocket.canCreateFreshReceiveAddress());
// We haven't used any key so the total must be 20 - 1 (the unused key)
assertEquals(19, pocket.getNumberIssuedReceiveAddresses());
assertEquals(19, pocket.getIssuedReceiveAddresses().size());
}
}
@Test
public void usedAddresses() throws Exception {
assertEquals(0, pocket.getUsedAddresses().size());
pocket.onConnection(getBlockchainConnection(DOGE));
// Receive and change addresses
assertEquals(13, pocket.getUsedAddresses().size());
}
private Sha256Hash send(Value value, WalletPocketHD w1, WalletPocketHD w2) throws Exception {
assertEquals(w1.getCoinType(), w2.getCoinType());
CoinType type = w1.getCoinType();
BitSendRequest req = w1.sendCoinsOffline(w2.getReceiveAddress(), value);
req.feePerTxSize = type.value("0.01");
w1.completeAndSignTx(req);
byte[] txBytes = req.tx.bitcoinSerialize();
w1.addNewTransactionIfNeeded(new BitTransaction(type, txBytes));
w2.addNewTransactionIfNeeded(new BitTransaction(type, txBytes));
return req.tx.getHash();
}
@Test
public void testSendingAndBalances() throws Exception {
DeterministicHierarchy h = new DeterministicHierarchy(masterKey);
WalletPocketHD account1 = new WalletPocketHD(h.get(BTC.getBip44Path(0), false, true), BTC, null, null);
WalletPocketHD account2 = new WalletPocketHD(h.get(BTC.getBip44Path(1), false, true), BTC, null, null);
WalletPocketHD account3 = new WalletPocketHD(h.get(BTC.getBip44Path(2), false, true), BTC, null, null);
Transaction tx = new Transaction(BTC);
tx.addOutput(BTC.oneCoin().toCoin(), account1.getReceiveAddress());
tx.getConfidence().setSource(Source.SELF);
account1.addNewTransactionIfNeeded(tx);
assertEquals(BTC.value("1"), account1.getBalance());
assertEquals(BTC.value("0"), account2.getBalance());
assertEquals(BTC.value("0"), account3.getBalance());
Sha256Hash txId = send(BTC.value("0.05"), account1, account2);
assertEquals(BTC.value("0.94"), account1.getBalance());
assertEquals(BTC.value("0"), account2.getBalance());
assertEquals(BTC.value("0"), account3.getBalance());
setTrustedTransaction(account1, txId);
setTrustedTransaction(account2, txId);
assertEquals(BTC.value("0.94"), account1.getBalance());
assertEquals(BTC.value("0.05"), account2.getBalance());
txId = send(BTC.value("0.07"), account1, account3);
setTrustedTransaction(account1, txId);
setTrustedTransaction(account3, txId);
assertEquals(BTC.value("0.86"), account1.getBalance());
assertEquals(BTC.value("0.05"), account2.getBalance());
assertEquals(BTC.value("0.07"), account3.getBalance());
txId = send(BTC.value("0.03"), account2, account3);
setTrustedTransaction(account2, txId);
setTrustedTransaction(account3, txId);
assertEquals(BTC.value("0.86"), account1.getBalance());
assertEquals(BTC.value("0.01"), account2.getBalance());
assertEquals(BTC.value("0.1"), account3.getBalance());
}
private void setTrustedTransaction(WalletPocketHD account, Sha256Hash txId) {
BitTransaction tx = checkNotNull(account.getTransaction(txId));
tx.setSource(Source.SELF);
}
@Test
public void testLoading() throws Exception {
assertFalse(pocket.isLoading());
pocket.onConnection(getBlockchainConnection(DOGE));
// TODO add fine grained control to the blockchain connection in order to test the loading status
assertFalse(pocket.isLoading());
}
@Test
public void fillTransactions() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
checkUnspentOutputs(getDummyUtxoSet(), pocket);
assertEquals(11000000000L, pocket.getBalance().value);
// Issued keys
assertEquals(18, pocket.keys.getNumIssuedExternalKeys());
assertEquals(9, pocket.keys.getNumIssuedInternalKeys());
// No addresses left to subscribe
List<AbstractAddress> addressesToWatch = pocket.getAddressesToWatch();
assertEquals(0, addressesToWatch.size());
// 18 external issued + 20 lookahead + 9 external issued + 20 lookahead
assertEquals(67, pocket.addressesStatus.size());
assertEquals(67, pocket.addressesSubscribed.size());
BitAddress receiveAddr = pocket.getReceiveAddress();
// This key is not issued
assertEquals(18, pocket.keys.getNumIssuedExternalKeys());
assertEquals(67, pocket.addressesStatus.size());
assertEquals(67, pocket.addressesSubscribed.size());
DeterministicKey key = pocket.keys.findKeyFromPubHash(receiveAddr.getHash160());
assertNotNull(key);
// 18 here is the key index, not issued keys count
assertEquals(18, key.getChildNumber().num());
assertEquals(11000000000L, pocket.getBalance().value);
}
@Test
public void serializeTransactionsBtc() throws Exception, Bip44KeyLookAheadExceededException {
WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null);
Transaction tx = new Transaction(BTC);
tx.addOutput(BTC.oneCoin().toCoin(), account.getReceiveAddress());
account.addNewTransactionIfNeeded(tx);
testWalletSerializationForCoin(account);
}
@Test
public void serializeTransactionsNbt() throws Exception, Bip44KeyLookAheadExceededException {
WalletPocketHD account = new WalletPocketHD(rootKey, NBT, null, null);
Transaction tx = new Transaction(NBT);
tx.addOutput(NBT.oneCoin().toCoin(), account.getReceiveAddress());
account.addNewTransactionIfNeeded(tx);
testWalletSerializationForCoin(account);
}
@Test
public void serializeTransactionsVpn() throws Exception, Bip44KeyLookAheadExceededException {
WalletPocketHD account = new WalletPocketHD(rootKey, VPN, null, null);
// Test tx with null extra bytes
Transaction tx = new Transaction(VPN);
tx.setTime(0x99999999);
tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress());
account.addNewTransactionIfNeeded(tx);
WalletPocketHD newAccount = testWalletSerializationForCoin(account);
Transaction newTx = newAccount.getRawTransaction(tx.getHash());
assertNotNull(newTx);
assertNotNull(newTx.getExtraBytes());
assertEquals(0, newTx.getExtraBytes().length);
// Test tx with empty extra bytes
tx = new Transaction(VPN);
tx.setTime(0x99999999);
tx.setExtraBytes(new byte[0]);
tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress());
account.addNewTransactionIfNeeded(tx);
newAccount = testWalletSerializationForCoin(account);
newTx = newAccount.getRawTransaction(tx.getHash());
assertNotNull(newTx);
assertNotNull(newTx.getExtraBytes());
assertEquals(0, newTx.getExtraBytes().length);
// Test tx with extra bytes
tx = new Transaction(VPN);
tx.setTime(0x99999999);
byte[] bytes = {0x1, 0x2, 0x3};
tx.setExtraBytes(bytes);
tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress());
account.addNewTransactionIfNeeded(tx);
newAccount = testWalletSerializationForCoin(account);
newTx = newAccount.getRawTransaction(tx.getHash());
assertNotNull(newTx);
assertArrayEquals(bytes, newTx.getExtraBytes());
}
private WalletPocketHD testWalletSerializationForCoin(WalletPocketHD account) throws UnreadableWalletException {
Protos.WalletPocket proto = account.toProtobuf();
WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null);
assertEquals(account.getBalance().value, newAccount.getBalance().value);
Map<Sha256Hash, BitTransaction> transactions = account.getTransactions();
Map<Sha256Hash, BitTransaction> newTransactions = newAccount.getTransactions();
for (Sha256Hash txId : transactions.keySet()) {
assertTrue(newTransactions.containsKey(txId));
assertEquals(transactions.get(txId), newTransactions.get(txId));
}
return newAccount;
}
@Test
public void serializeUnencryptedNormal() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
Protos.WalletPocket walletPocketProto = pocket.toProtobuf();
System.out.println(walletPocketProto.toString());
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null);
assertEquals(pocket.getBalance().value, newPocket.getBalance().value);
assertEquals(DOGE.value(11000000000l), newPocket.getBalance());
Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet();
checkUnspentOutputs(expectedUtxoSet, pocket);
checkUnspentOutputs(expectedUtxoSet, newPocket);
assertEquals(pocket.getCoinType(), newPocket.getCoinType());
assertEquals(pocket.getDescriptionOrCoinName(), newPocket.getDescriptionOrCoinName());
assertEquals(pocket.keys.toProtobuf().toString(), newPocket.keys.toProtobuf().toString());
assertEquals(pocket.getLastBlockSeenHash(), newPocket.getLastBlockSeenHash());
assertEquals(pocket.getLastBlockSeenHeight(), newPocket.getLastBlockSeenHeight());
assertEquals(pocket.getLastBlockSeenTimeSecs(), newPocket.getLastBlockSeenTimeSecs());
for (BitTransaction tx : pocket.getTransactions().values()) {
assertEquals(tx, newPocket.getTransaction(tx.getHash()));
BitTransaction txNew = checkNotNull(newPocket.getTransaction(tx.getHash()));
assertInputsEquals(tx.getInputs(), txNew.getInputs());
assertOutputsEquals(tx.getOutputs(false), txNew.getOutputs(false));
}
for (AddressStatus status : pocket.getAllAddressStatus()) {
if (status.getStatus() == null) continue;
assertEquals(status, newPocket.getAddressStatus(status.getAddress()));
}
// Issued keys
assertEquals(18, newPocket.keys.getNumIssuedExternalKeys());
assertEquals(9, newPocket.keys.getNumIssuedInternalKeys());
newPocket.onConnection(getBlockchainConnection(DOGE));
// No addresses left to subscribe
List<AbstractAddress> addressesToWatch = newPocket.getAddressesToWatch();
assertEquals(0, addressesToWatch.size());
// 18 external issued + 20 lookahead + 9 external issued + 20 lookahead
assertEquals(67, newPocket.addressesStatus.size());
assertEquals(67, newPocket.addressesSubscribed.size());
}
private void assertInputsEquals(List<TransactionInput> expected, List<TransactionInput> actual) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize());
}
}
private void assertOutputsEquals(List<TransactionOutput> expected, List<TransactionOutput> actual) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize());
}
}
@Test
public void serializeUnencryptedEmpty() throws Exception {
pocket.maybeInitializeAllKeys();
Protos.WalletPocket walletPocketProto = pocket.toProtobuf();
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null);
assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString());
// Issued keys
assertEquals(0, newPocket.keys.getNumIssuedExternalKeys());
assertEquals(0, newPocket.keys.getNumIssuedInternalKeys());
// 20 lookahead + 20 lookahead
assertEquals(40, newPocket.keys.getActiveKeys().size());
}
@Test
public void serializeEncryptedEmpty() throws Exception {
pocket.maybeInitializeAllKeys();
pocket.encrypt(crypter, aesKey);
Protos.WalletPocket walletPocketProto = pocket.toProtobuf();
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, crypter);
assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString());
pocket.decrypt(aesKey);
// One is encrypted, so they should not match
assertNotEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString());
newPocket.decrypt(aesKey);
assertEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString());
}
@Test
public void serializeEncryptedNormal() throws Exception {
pocket.maybeInitializeAllKeys();
pocket.encrypt(crypter, aesKey);
pocket.onConnection(getBlockchainConnection(DOGE));
assertEquals(DOGE.value(11000000000l), pocket.getBalance());
assertAllKeysEncrypted(pocket);
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(pocket.toProtobuf(), crypter);
assertEquals(DOGE.value(11000000000l), newPocket.getBalance());
Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet();
checkUnspentOutputs(expectedUtxoSet, pocket);
checkUnspentOutputs(expectedUtxoSet, newPocket);
assertAllKeysEncrypted(newPocket);
pocket.decrypt(aesKey);
newPocket.decrypt(aesKey);
assertAllKeysDecrypted(pocket);
assertAllKeysDecrypted(newPocket);
}
private void checkUnspentOutputs(Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet, WalletPocketHD pocket) {
Map<TrimmedOutPoint, OutPointOutput> pocketUtxoSet = pocket.getUnspentOutputs(false);
for (OutPointOutput utxo : expectedUtxoSet.values()) {
assertEquals(utxo, pocketUtxoSet.get(utxo.getOutPoint()));
}
}
private void assertAllKeysDecrypted(WalletPocketHD pocket) {
List<ECKey> keys = pocket.keys.getKeys(false);
for (ECKey k : keys) {
DeterministicKey key = (DeterministicKey) k;
assertFalse(key.isEncrypted());
}
}
private void assertAllKeysEncrypted(WalletPocketHD pocket) {
List<ECKey> keys = pocket.keys.getKeys(false);
for (ECKey k : keys) {
DeterministicKey key = (DeterministicKey) k;
assertTrue(key.isEncrypted());
}
}
@Test
public void createDustTransactionFee() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp");
Value softDust = DOGE.getSoftDustLimit();
assertNotNull(softDust);
// Send a soft dust
BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, softDust.subtract(DOGE.value(1)));
pocket.completeTransaction(sendRequest);
assertEquals(DOGE.getFeeValue().multiply(2), sendRequest.tx.getFee());
}
@Test
public void createTransactionAndBroadcast() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp");
Value orgBalance = pocket.getBalance();
BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, DOGE.value(AMOUNT_TO_SEND));
sendRequest.shuffleOutputs = false;
sendRequest.feePerTxSize = DOGE.value(0);
pocket.completeTransaction(sendRequest);
// FIXME, mock does not work here
// pocket.broadcastTx(tx);
pocket.addNewTransactionIfNeeded(sendRequest.tx);
assertEquals(orgBalance.subtract(AMOUNT_TO_SEND), pocket.getBalance());
}
// Util methods
////////////////////////////////////////////////////////////////////////////////////////////////
public class MessageComparator implements Comparator<ChildMessage> {
@Override
public int compare(ChildMessage o1, ChildMessage o2) {
String s1 = Utils.HEX.encode(o1.bitcoinSerialize());
String s2 = Utils.HEX.encode(o2.bitcoinSerialize());
return s1.compareTo(s2);
}
}
HashMap<AbstractAddress, AddressStatus> getDummyStatuses() throws AddressMalformedException {
HashMap<AbstractAddress, AddressStatus> status = new HashMap<>(40);
for (int i = 0; i < addresses.size(); i++) {
AbstractAddress address = DOGE.newAddress(addresses.get(i));
status.put(address, new AddressStatus(address, statuses[i]));
}
return status;
}
private HashMap<AbstractAddress, ArrayList<HistoryTx>> getDummyHistoryTXs() throws AddressMalformedException, JSONException {
HashMap<AbstractAddress, ArrayList<HistoryTx>> htxs = new HashMap<>(40);
for (int i = 0; i < statuses.length; i++) {
JSONArray jsonArray = new JSONArray(history[i]);
ArrayList<HistoryTx> list = new ArrayList<>();
for (int j = 0; j < jsonArray.length(); j++) {
list.add(new HistoryTx(jsonArray.getJSONObject(j)));
}
htxs.put(DOGE.newAddress(addresses.get(i)), list);
}
return htxs;
}
private HashMap<AbstractAddress, ArrayList<UnspentTx>> getDummyUnspentTXs() throws AddressMalformedException, JSONException {
HashMap<AbstractAddress, ArrayList<UnspentTx>> utxs = new HashMap<>(40);
for (int i = 0; i < statuses.length; i++) {
JSONArray jsonArray = new JSONArray(unspent[i]);
ArrayList<UnspentTx> list = new ArrayList<>();
for (int j = 0; j < jsonArray.length(); j++) {
list.add(new UnspentTx(jsonArray.getJSONObject(j)));
}
utxs.put(DOGE.newAddress(addresses.get(i)), list);
}
return utxs;
}
private Map<TrimmedOutPoint, OutPointOutput> getDummyUtxoSet() throws AddressMalformedException, JSONException {
final HashMap<TrimmedOutPoint, OutPointOutput> unspentOutputs = new HashMap<>();
for (int i = 0; i < statuses.length; i++) {
BitAddress address = (BitAddress) DOGE.newAddress(addresses.get(i));
JSONArray utxoArray = new JSONArray(unspent[i]);
for (int j = 0; j < utxoArray.length(); j++) {
JSONObject utxoObject = utxoArray.getJSONObject(j);
//"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]",
TrimmedOutPoint outPoint = new TrimmedOutPoint(DOGE, utxoObject.getInt("tx_pos"),
new Sha256Hash(utxoObject.getString("tx_hash")));
TransactionOutput output = new TransactionOutput(DOGE, null,
Coin.valueOf(utxoObject.getLong("value")), address);
OutPointOutput utxo = new OutPointOutput(outPoint, output, false);
unspentOutputs.put(outPoint, utxo);
}
}
return unspentOutputs;
}
private HashMap<Sha256Hash, byte[]> getDummyRawTXs() throws AddressMalformedException, JSONException {
HashMap<Sha256Hash, byte[]> rawTxs = new HashMap<>();
for (String[] tx : txs) {
rawTxs.put(new Sha256Hash(tx[0]), Utils.HEX.decode(tx[1]));
}
return rawTxs;
}
class MockBlockchainConnection implements BitBlockchainConnection {
final HashMap<AbstractAddress, AddressStatus> statuses;
final HashMap<AbstractAddress, ArrayList<HistoryTx>> historyTxs;
final HashMap<AbstractAddress, ArrayList<UnspentTx>> unspentTxs;
final HashMap<Sha256Hash, byte[]> rawTxs;
private CoinType coinType;
MockBlockchainConnection(CoinType coinType) throws Exception {
this.coinType = coinType;
statuses = getDummyStatuses();
historyTxs = getDummyHistoryTXs();
unspentTxs = getDummyUnspentTXs();
rawTxs = getDummyRawTXs();
}
@Override
public void getBlock(int height, TransactionEventListener<BitTransaction> listener) { }
@Override
public void subscribeToBlockchain(TransactionEventListener<BitTransaction> listener) {
listener.onNewBlock(new BlockHeader(coinType, blockTimestamp, blockHeight));
}
@Override
public void subscribeToAddresses(List<AbstractAddress> addresses, TransactionEventListener<BitTransaction> listener) {
for (AbstractAddress a : addresses) {
AddressStatus status = statuses.get(a);
if (status == null) {
status = new AddressStatus(a, null);
}
listener.onAddressStatusUpdate(status);
}
}
@Override
public void getHistoryTx(AddressStatus status, TransactionEventListener<BitTransaction> listener) {
List<HistoryTx> htx = historyTxs.get(status.getAddress());
if (htx == null) {
htx = ImmutableList.of();
}
listener.onTransactionHistory(status, htx);
}
@Override
public void getUnspentTx(AddressStatus status, BitTransactionEventListener listener) {
List<UnspentTx> utx = unspentTxs.get(status.getAddress());
if (utx == null) {
utx = ImmutableList.of();
}
listener.onUnspentTransactionUpdate(status, utx);
}
@Override
public void getTransaction(Sha256Hash txHash, TransactionEventListener<BitTransaction> listener) {
BitTransaction tx = new BitTransaction(coinType, rawTxs.get(txHash));
listener.onTransactionUpdate(tx);
}
@Override
public void broadcastTx(BitTransaction tx, TransactionEventListener<BitTransaction> listener) {
// List<AddressStatus> newStatuses = new ArrayList<AddressStatus>();
// Random rand = new Random();
// byte[] randBytes = new byte[32];
// // Get spent outputs and modify statuses
// for (TransactionInput txi : tx.getInputs()) {
// UnspentTx unspentTx = new UnspentTx(
// txi.getOutpoint(), txi.getValue().value, 0);
//
// for (Map.Entry<Address, ArrayList<UnspentTx>> entry : utxs.entrySet()) {
// if (entry.getValue().remove(unspentTx)) {
// rand.nextBytes(randBytes);
// AddressStatus newStatus = new AddressStatus(entry.getKey(), Utils.HEX.encode(randBytes));
// statuses.put(entry.getKey(), newStatus);
// newStatuses.add(newStatus);
// }
// }
// }
//
// for (TransactionOutput txo : tx.getOutputs()) {
// if (txo.getAddressFromP2PKHScript(coinType) != null) {
// Address address = txo.getAddressFromP2PKHScript(coinType);
// if (addresses.contains(address.toString())) {
// AddressStatus newStatus = new AddressStatus(address, tx.getHashAsString());
// statuses.put(address, newStatus);
// newStatuses.add(newStatus);
// if (!utxs.containsKey(address)) {
// utxs.put(address, new ArrayList<UnspentTx>());
// }
// ArrayList<UnspentTx> unspentTxs = utxs.get(address);
// unspentTxs.add(new UnspentTx(txo.getOutPointFor(),
// txo.getValue().value, 0));
// if (!historyTxs.containsKey(address)) {
// historyTxs.put(address, new ArrayList<HistoryTx>());
// }
// ArrayList<HistoryTx> historyTxes = historyTxs.get(address);
// historyTxes.add(new HistoryTx(txo.getOutPointFor(), 0));
// }
// }
// }
//
// rawTxs.put(tx.getHash(), tx.bitcoinSerialize());
//
// for (AddressStatus newStatus : newStatuses) {
// listener.onAddressStatusUpdate(newStatus);
// }
}
@Override
public boolean broadcastTxSync(BitTransaction tx) {
return false;
}
@Override
public void ping(String versionString) {}
@Override
public void addEventListener(ConnectionEventListener listener) {
}
@Override
public void resetConnection() {
}
@Override
public void stopAsync() {
}
@Override
public boolean isActivelyConnected() {
return false;
}
@Override
public void startAsync() {
}
}
private MockBlockchainConnection getBlockchainConnection(CoinType coinType) throws Exception {
return new MockBlockchainConnection(coinType);
}
// Mock data
long blockTimestamp = 1411000000l;
int blockHeight = 200000;
List<String> addresses = ImmutableList.of(
"nnfP8VuPfZXhNtMDzvX1bKurzcV1k7HNrQ",
"nf4AUKiaGdx4GTbbh222KvtuCbAuvbcdE2",
"npGkmbWtdWybFNSZQXUK6zZxbEocMtrTzz",
"nVaN45bbs6AUc1EUpP71hHGBGb2qciNrJc",
"nrdHFZP1AfdKBrjsSQmwFm8R2i2mzMef75",
"niGZgfbhFYn6tJqksmC8CnzSRL1GHNsu7e",
"nh6w8yu1zoKYoT837ffkVmuPjTaP69Pc5E",
"nbyMgmEghsL9tpk7XfdH9gLGudh6Lrbbuf",
"naX9akzYuWY1gKbcZo3t36aBKc1gqbzgSs",
"nqcPVTGeAfCowELB2D5PdVF3FWFjFtkkFf",
"nd4vVvPTpp2LfcsMPsmG3Dh7MFAsqRHp4g",
"nVK4Uz5Sf56ygrr6RiwXcRvH8AuUVbjjHi",
"nbipkRwT1NCSXZSrm8uAAEgQAA2s2NWMkG",
"nZU6QAMAdCQcVDxEmL7GEY6ykFm8m6u6am",
"nbFqayssM5s7hLjLFwf2d95JXKRWBk2pBH",
"nacZfcNgVi47hamLscWdUGQhUQGGpSdgq8",
"niiMT7ZYeFnaLPYtqQFBBX1sP3dT5JtcEw",
"ns6GyTaniLWaiYrvAf5tk4D8tWrbcCLGyj",
"nhdwQfptLTzLJGbLF3vvtqyBaqPMPecDmE",
"neMUAGeTzwxLbSkXMsdmWf1fTKS1UsJjXY",
"nXsAMeXxtpx8jaxnU3Xv9ZQ6ZcRcD1xYhR",
"ns35rKnnWf6xP3KSj5WPkMCVVaADGi6Ndk",
"nk4wcXYBEWs5HkhNLsuaQJoAjJHoK6SQmG",
"npsJQWu8fsALoTPum8D4j8FDkyeusk8fU8",
"nZNhZo4Vz3DnwQGPL3SJTZgUw2Kh4g9oay",
"nnxDTYB8WMHMgLnCY2tuaEtysvdhRnWehZ",
"nb2iaDXG1EqkcE47H87WQFkQNkeVK66Z21",
"nWHAkpn2DB3DJRsbiK3vpbigoa3M2uVuF8",
"nViKdC7Gm6TMmCuWTBwVE9i4rJhyfwbfqg",
"nZQV5BifbGPzaxTrB4efgHruWH5rufemqP",
"nVvZaLvnkCVAzpLYPoHeqU4w9zJ5yrZgUn",
"nrMp6pRCk98WYWkCWq9Pqthz9HbpQu8BT3",
"nnA3aYsLqysKT6gAu1dr4EKm586cmKiRxS",
"nVfcVgMY7DL6nqoSxwJy7B7hKXirQwj6ic",
"ni4oAzi6nCVuEdjoHyVMVKWb1DqTd3qY3H",
"nnpf3gx442yomniRJPMGPapgjHrraPZXxJ",
"nkuFnF8wUmHFkMycaFMvyjBoiMeR5KBKGd",
"nXKccwjaUyrQkLrdqKT6aq6cDiFgBBVgNz",
"nZMSNsXSAL7i1YD6KP5FrhATuZ2CWvnxqR",
"nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q"
);
String[] statuses = {
"fe7c109d8bd90551a406cf0b3499117db04bc9c4f48e1df27ac1cf3ddcb3d464",
"8a53babd831c6c3a857e20190e884efe75a005bdd7cd273c4f27ab1b8ec81c2d",
"86bc2f0cf0112fd59c9aadfe5c887062c21d7a873db260dff68dcfe4417fe212",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
};
String[] unspent = {
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 1, \"value\": 1000000000, \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 2, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"tx_pos\": 0, \"value\": 1000000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 3, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 4, \"value\": 1000000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 12, \"value\": 1000000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 13, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 6, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 7, \"value\": 1000000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 8, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 9, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 10, \"value\": 1000000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]"
};
String[] history = {
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]"
};
String[][] txs = {
{"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f", "0100000001b8778dff640ccb144346d9db48201639b2707a0cc59e19672d2dd76cc6d1a5a6010000006b48304502210098d2e5b8a6c72442430bc09f2f4bcb56612c5b9e5eee821d65b412d099bb723402204f7f008ac052e5d7be0ab5b0c85ea5e627d725a521bd9e9b193d1fdf81c317a0012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0e0065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00ca9a3b000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac0065cd1d000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac0065cd1d000000001976a9140f2b1e5b376e22c5d1e635233eb90cf50ad9095188ac00ca9a3b000000001976a914f612ffd50b6a69df5e34ee0c5b529dfaaedca03d88ac00f633bce60000001976a914937258e3a8c463ec07e78ce62326c488170ad25e88ac0065cd1d000000001976a9142848ad5ff4cc32df3649646017c47bc04e8d211788ac00ca9a3b000000001976a914fa937737a6df2b8a5e39cce8b0bdd9510683023a88ac0065cd1d000000001976a914ae248a5d710143b6b309aaab9ce17059536e2aa388ac0065cd1d000000001976a91438d6eb11eca405be497a7183c50e437851425e0088ac00ca9a3b000000001976a91410ac6b2704146b50a1dd8f6df70736856ebf8b3488ac0065cd1d000000001976a914456816dccb3a4f33ae2dbd3ba623997075d5c73d88ac00ca9a3b000000001976a91452957c44e5bee9a60402a739fc8959c2850ea98488ac0065cd1d000000001976a914fb2dffa402d05f74335d137e21e41d8920c745fb88ac00000000"},
{"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae", "01000000011a656d67706db286d1e6fad57eb4f411cb14f8880cea8348da339b9d434a5ec7050000006a47304402201d69fddb269b53aa742ff6437a45adb4ca5c59f666c9b4eabc4a0c7a6e6f4c0f022015a747b7a6d9371a4020f5b396dcd094b0f36af3fc82e95091da856181912dfa012102c9a8d5b2f768afe30ee772d185e7a61f751be05649a79508b38a2be8824adec3ffffffff020065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00b07098e60000001976a9141630d812e219e6bcbe494eb96f7a7900c216ad5d88ac00000000"},
{"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb", "010000000164a3990893c012b20287d43d1071ac26f4b93648ff4213db6da6979beed6b7dc010000006b48304502210086ac11d4a8146b4176a72059960690c72a9776468cd671fd07c064b51f24961d02205bcf008d6995014f3cfd79100ee9beab5688c88cca15c5cea38b769563785d900121036530415a7b3b9c5976f26a63a57d119ab39491762121723c773399a2531a1bd7ffffffff020065cd1d000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac006aad74e60000001976a914e5616848352c328c9f61b167eb1b0fde39b5cb6788ac00000000"},
{"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7", "010000000141c217dfea3a1d8d6a06e9d3daf75b292581f652256d73a7891e5dc9c7ee3cca000000006a47304402205cce451228f98fece9645052546b82c2b2d425a4889b03999001fababfc7f4690220583b2189faef07d6b0191c788301cfab1b3f47ffe2c403d632b92c6dde27e14f012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0100ca9a3b000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac00000000"}
};
} | BOLI-Project/AndroidWallet | core/src/test/java/com/boli/core/wallet/WalletPocketHDTest.java |
45,860 | package aQute.tester.junit.platform.test;
import static aQute.junit.constants.TesterConstants.TESTER_CONTINUOUS;
import static aQute.junit.constants.TesterConstants.TESTER_CONTROLPORT;
import static aQute.junit.constants.TesterConstants.TESTER_NAMES;
import static aQute.junit.constants.TesterConstants.TESTER_PORT;
import static aQute.junit.constants.TesterConstants.TESTER_UNRESOLVED;
import static aQute.tester.test.utils.TestRunData.nameOf;
import static org.eclipse.jdt.internal.junit.model.ITestRunListener2.STATUS_FAILURE;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.assertj.core.api.Assertions;
import org.junit.AssumptionViolatedException;
import org.junit.ComparisonFailure;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.JUnitException;
import org.opentest4j.AssertionFailedError;
import org.opentest4j.MultipleFailuresError;
import org.opentest4j.TestAbortedException;
import org.osgi.framework.Bundle;
import org.w3c.dom.Document;
import org.xmlunit.assertj.XmlAssert;
import aQute.launchpad.LaunchpadBuilder;
import aQute.lib.io.IO;
import aQute.lib.xml.XML;
import aQute.tester.test.assertions.CustomAssertionError;
import aQute.tester.test.utils.ServiceLoaderMask;
import aQute.tester.test.utils.TestEntry;
import aQute.tester.test.utils.TestFailure;
import aQute.tester.test.utils.TestRunData;
import aQute.tester.test.utils.TestRunListener;
import aQute.tester.testbase.AbstractActivatorTest;
import aQute.tester.testclasses.JUnit3Test;
import aQute.tester.testclasses.JUnit4Test;
import aQute.tester.testclasses.With1Error1Failure;
import aQute.tester.testclasses.With2Failures;
import aQute.tester.testclasses.junit.platform.JUnit3ComparisonTest;
import aQute.tester.testclasses.junit.platform.JUnit4AbortTest;
import aQute.tester.testclasses.junit.platform.JUnit4ComparisonTest;
import aQute.tester.testclasses.junit.platform.JUnit4Skipper;
import aQute.tester.testclasses.junit.platform.JUnit5AbortTest;
import aQute.tester.testclasses.junit.platform.JUnit5ContainerError;
import aQute.tester.testclasses.junit.platform.JUnit5ContainerFailure;
import aQute.tester.testclasses.junit.platform.JUnit5ContainerSkipped;
import aQute.tester.testclasses.junit.platform.JUnit5ContainerSkippedWithCustomDisplayName;
import aQute.tester.testclasses.junit.platform.JUnit5DisplayNameTest;
import aQute.tester.testclasses.junit.platform.JUnit5ParameterizedTest;
import aQute.tester.testclasses.junit.platform.JUnit5SimpleComparisonTest;
import aQute.tester.testclasses.junit.platform.JUnit5Skipper;
import aQute.tester.testclasses.junit.platform.JUnit5Test;
import aQute.tester.testclasses.junit.platform.JUnitMixedComparisonTest;
import aQute.tester.testclasses.junit.platform.Mixed35Test;
import aQute.tester.testclasses.junit.platform.Mixed45Test;
import aQute.tester.testclasses.junit.platform.ParameterizedTesterNamesTest;
public class ActivatorJUnitPlatformTest extends AbstractActivatorTest {
public ActivatorJUnitPlatformTest() {
super("aQute.tester.junit.platform.Activator", "biz.aQute.tester.junit-platform");
}
// We have the Jupiter engine on the classpath so that the tests will run.
// This classloader will hide it from the framework-under-test.
static final ClassLoader SERVICELOADER_MASK = new ServiceLoaderMask();
@Override
protected void createLP() {
builder.usingClassLoader(SERVICELOADER_MASK);
super.createLP();
}
@Test
public void multipleMixedTests_areAllRun_withJupiterTest() {
final ExitCode exitCode = runTests(JUnit3Test.class, JUnit4Test.class, JUnit5Test.class);
assertThat(exitCode.exitCode).as("exit code")
.isZero();
assertThat(testBundler.getCurrentThread(JUnit3Test.class)).as("junit3")
.isSameAs(Thread.currentThread());
assertThat(testBundler.getCurrentThread(JUnit4Test.class)).as("junit4")
.isSameAs(Thread.currentThread());
assertThat(testBundler.getCurrentThread(JUnit5Test.class)).as("junit5")
.isSameAs(Thread.currentThread());
}
@SuppressWarnings("unchecked")
@Test
public void multipleMixedTests_inASingleTestCase_areAllRun() {
final ExitCode exitCode = runTests(Mixed35Test.class, Mixed45Test.class);
assertThat(exitCode.exitCode).as("exit code")
.isZero();
assertThat(testBundler.getStatic(Mixed35Test.class, Set.class, "methods")).as("Mixed JUnit 3 & 5")
.containsExactlyInAnyOrder("testJUnit3", "junit5Test");
assertThat(testBundler.getStatic(Mixed45Test.class, Set.class, "methods")).as("Mixed JUnit 4 & 5")
.containsExactlyInAnyOrder("junit4Test", "junit5Test");
}
@Test
public void eclipseListener_reportsResults_acrossMultipleBundles() throws InterruptedException {
Class<?>[][] tests = {
{
With2Failures.class, JUnit4Test.class
}, {
With1Error1Failure.class, JUnit5Test.class
}
};
TestRunData result = runTestsEclipse(tests);
assertThat(result.getTestCount()).as("testCount")
.isEqualTo(9);
// @formatter:off
assertThat(result.getNameMap()
.keySet()).as("executed")
.contains(
nameOf(With2Failures.class),
nameOf(With2Failures.class, "test1"),
nameOf(With2Failures.class, "test2"),
nameOf(With2Failures.class, "test3"),
nameOf(JUnit4Test.class),
nameOf(JUnit4Test.class, "somethingElse"),
nameOf(With1Error1Failure.class),
nameOf(With1Error1Failure.class, "test1"),
nameOf(With1Error1Failure.class, "test2"),
nameOf(With1Error1Failure.class, "test3"),
nameOf(JUnit5Test.class, "somethingElseAgain"),
nameOf(testBundles.get(0)),
nameOf(testBundles.get(1))
);
assertThat(result).as("result")
.hasFailedTest(With2Failures.class, "test1", AssertionError.class)
.hasSuccessfulTest(With2Failures.class, "test2")
.hasFailedTest(With2Failures.class, "test3", CustomAssertionError.class)
.hasSuccessfulTest(JUnit4Test.class, "somethingElse")
.hasErroredTest(With1Error1Failure.class, "test1", RuntimeException.class)
.hasSuccessfulTest(With1Error1Failure.class, "test2")
.hasFailedTest(With1Error1Failure.class, "test3", AssertionError.class)
.hasSuccessfulTest(JUnit5Test.class, "somethingElseAgain")
;
// @formatter:on
}
private void readWithTimeout(InputStream inStr) throws Exception {
long endTime = System.currentTimeMillis() + 10000;
int available;
while ((available = inStr.available()) == 0 && System.currentTimeMillis() < endTime) {
Thread.sleep(10);
}
if (available == 0) {
Assertions.fail("Timeout waiting for data");
}
assertThat(available).as("control signal")
.isEqualTo(1);
int value = inStr.read();
assertThat(value).as("control value")
.isNotEqualTo(-1);
}
@Test
public void eclipseListener_worksInContinuousMode_withControlSocket() throws Exception {
try (ServerSocket controlSock = new ServerSocket(0)) {
controlSock.setSoTimeout(10000);
int controlPort = controlSock.getLocalPort();
builder.set("launch.services", "true")
.set(TESTER_CONTINUOUS, "true")
// This value should be ignored
.set(TESTER_PORT, Integer.toString(controlPort - 2))
.set(TESTER_CONTROLPORT, Integer.toString(controlPort));
createLP();
addTestBundle(With2Failures.class, JUnit4Test.class);
runTester();
try (Socket sock = controlSock.accept()) {
InputStream inStr = sock.getInputStream();
DataOutputStream outStr = new DataOutputStream(sock.getOutputStream());
readWithTimeout(inStr);
TestRunListener listener = startEclipseJUnitListener();
outStr.writeInt(eclipseJUnitPort);
outStr.flush();
listener.waitForClientToFinish(10000);
TestRunData result = listener.getLatestRunData();
if (result == null) {
fail("Result was null" + listener);
// To prevent NPE and allow any soft assertions to be
// displayed.
return;
}
assertThat(result.getTestCount()).as("testCount")
.isEqualTo(5);
// @formatter:off
assertThat(result.getNameMap()
.keySet()).as("executed")
.contains(
nameOf(With2Failures.class),
nameOf(With2Failures.class, "test1"),
nameOf(With2Failures.class, "test2"),
nameOf(With2Failures.class, "test3"),
nameOf(JUnit4Test.class),
nameOf(JUnit4Test.class, "somethingElse"),
nameOf(testBundles.get(0))
);
assertThat(result).as("result")
.hasFailedTest(With2Failures.class, "test1", AssertionError.class)
.hasSuccessfulTest(With2Failures.class, "test2")
.hasFailedTest(With2Failures.class, "test3", CustomAssertionError.class)
.hasSuccessfulTest(JUnit4Test.class, "somethingElse")
;
// @formatter:on
addTestBundle(With1Error1Failure.class, JUnit5Test.class);
readWithTimeout(inStr);
listener = startEclipseJUnitListener();
outStr.writeInt(eclipseJUnitPort);
outStr.flush();
listener.waitForClientToFinish(10000);
result = listener.getLatestRunData();
if (result == null) {
fail("Eclipse didn't capture output from the second run");
return;
}
int i = 2;
assertThat(result.getTestCount()).as("testCount:" + i)
.isEqualTo(4);
// @formatter:off
assertThat(result.getNameMap()
.keySet()).as("executed:2")
.contains(
nameOf(With1Error1Failure.class),
nameOf(With1Error1Failure.class, "test1"),
nameOf(With1Error1Failure.class, "test2"),
nameOf(With1Error1Failure.class, "test3"),
nameOf(JUnit5Test.class, "somethingElseAgain"),
nameOf(testBundles.get(1))
);
assertThat(result).as("result:2")
.hasErroredTest(With1Error1Failure.class, "test1", RuntimeException.class)
.hasSuccessfulTest(With1Error1Failure.class, "test2")
.hasFailedTest(With1Error1Failure.class, "test3", AssertionError.class)
.hasSuccessfulTest(JUnit5Test.class, "somethingElseAgain")
;
// @formatter:on
}
}
}
@Test
public void eclipseListener_reportsComparisonFailures() throws InterruptedException {
Class<?>[] tests = {
JUnit3ComparisonTest.class, JUnit4ComparisonTest.class, JUnit5SimpleComparisonTest.class, JUnit5Test.class,
JUnitMixedComparisonTest.class
};
TestRunData result = runTestsEclipse(tests);
final String[] order = {
"1", "2", "3.1", "3.2", "3.4", "4"
};
// @formatter:off
assertThat(result).as("result")
.hasFailedTest(JUnit3ComparisonTest.class, "testComparisonFailure", junit.framework.ComparisonFailure.class, "expected", "actual")
.hasFailedTest(JUnit4ComparisonTest.class, "comparisonFailure", ComparisonFailure.class, "expected", "actual")
.hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class, "expected", "actual")
.hasFailedTest(JUnitMixedComparisonTest.class, "multipleComparisonFailure", MultipleFailuresError.class,
Stream.of(order).map(x -> "expected" + x).collect(Collectors.joining("\n\n")),
Stream.of(order).map(x -> "actual" + x).collect(Collectors.joining("\n\n"))
)
;
// @formatter:on
TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure"));
assertThat(f).as("emptyComparisonFailure")
.isNotNull();
if (f != null) {
assertThat(f.status).as("emptyComparisonFailure:status")
.isEqualTo(STATUS_FAILURE);
assertThat(f.expected).as("emptyComparisonFailure:expected")
.isNull();
assertThat(f.actual).as("emptyComparisonFailure:actual")
.isNull();
}
}
@Test
public void eclipseListener_reportsParameterizedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5ParameterizedTest.class);
TestEntry methodTest = result.getTest(JUnit5ParameterizedTest.class, "parameterizedMethod");
if (methodTest == null) {
fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, "parameterizedMethod"));
return;
}
assertThat(methodTest.parameterTypes).as("parameterTypes")
.containsExactly("java.lang.String", "float");
List<TestEntry> parameterTests = result.getChildrenOf(methodTest.testId)
.stream()
.map(x -> result.getById(x))
.collect(Collectors.toList());
assertThat(parameterTests.stream()
.map(x -> x.testName)).as("testNames")
.allMatch(x -> x.equals(nameOf(JUnit5ParameterizedTest.class, "parameterizedMethod")));
assertThat(parameterTests.stream()).as("dynamic")
.allMatch(x -> x.isDynamicTest);
assertThat(parameterTests.stream()
.map(x -> x.displayName)).as("displayNames")
.containsExactlyInAnyOrder("1 ==> param: 'one', param2: 1.0", "2 ==> param: 'two', param2: 2.0",
"3 ==> param: 'three', param2: 3.0", "4 ==> param: 'four', param2: 4.0",
"5 ==> param: 'five', param2: 5.0");
Optional<TestEntry> test4 = parameterTests.stream()
.filter(x -> x.displayName.startsWith("4 ==>"))
.findFirst();
if (!test4.isPresent()) {
fail("Couldn't find test result for parameter 4");
} else {
assertThat(parameterTests.stream()
.filter(x -> result.getFailure(x.testId) != null)).as("failures")
.containsExactly(test4.get());
}
}
@Test
public void eclipseListener_reportsMisconfiguredParameterizedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5ParameterizedTest.class);
TestEntry methodTest = result.getTest(JUnit5ParameterizedTest.class, "misconfiguredMethod");
if (methodTest == null) {
fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, "misconfiguredMethod"));
return;
}
TestFailure failure = result.getFailure(methodTest.testId);
if (failure == null) {
fail("Expecting method:\n%s\nto have failed", methodTest);
} else {
assertThat(failure.trace).as("trace")
.startsWith("org.junit.platform.commons.JUnitException: Could not find factory method [unknownMethod]");
}
}
@Test
public void eclipseListener_reportsCustomNames_withOddCharacters() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5DisplayNameTest.class);
final String[] methodList = {
"test1", "testWithNonASCII", "testWithNonLatin"
};
final String[] displayList = {
// "Test 1", "Prüfung 2", "Δοκιμή 3"
"Test 1", "Pr\u00fcfung 2", "\u0394\u03bf\u03ba\u03b9\u03bc\u03ae 3"
};
for (int i = 0; i < methodList.length; i++) {
final String method = methodList[i];
final String display = displayList[i];
TestEntry methodTest = result.getTest(JUnit5DisplayNameTest.class, method);
if (methodTest == null) {
fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, method));
continue;
}
assertThat(methodTest.displayName).as(String.format("[%d] %s", i, method))
.isEqualTo(display);
}
}
@Test
public void eclipseListener_reportsSkippedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5Skipper.class, JUnit5ContainerSkipped.class,
JUnit5ContainerSkippedWithCustomDisplayName.class, JUnit4Skipper.class);
assertThat(result).as("result")
.hasSkippedTest(JUnit5Skipper.class, "disabledTest", "with custom message")
.hasSkippedTest(JUnit5ContainerSkipped.class, "with another message")
.hasSkippedTest(JUnit5ContainerSkipped.class, "disabledTest2",
"ancestor \"JUnit5ContainerSkipped\" was skipped")
.hasSkippedTest(JUnit5ContainerSkipped.class, "disabledTest3",
"ancestor \"JUnit5ContainerSkipped\" was skipped")
.hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "with a third message")
.hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "disabledTest2",
"ancestor \"Skipper Class\" was skipped")
.hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "disabledTest3",
"ancestor \"Skipper Class\" was skipped")
.hasSkippedTest(JUnit4Skipper.class, "disabledTest", "This is a test");
}
@Test
public void eclipseListener_reportsAbortedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5AbortTest.class, JUnit4AbortTest.class);
assertThat(result).as("result")
.hasAbortedTest(JUnit5AbortTest.class, "abortedTest",
new TestAbortedException("Assumption failed: I just can't go on"))
.hasAbortedTest(JUnit4AbortTest.class, "abortedTest",
new AssumptionViolatedException("Let's get outta here"));
}
@Test
public void eclipseListener_handlesNoEnginesGracefully() throws Exception {
try (LaunchpadBuilder builder = new LaunchpadBuilder()) {
IO.close(this.builder);
builder.bndrun("no-engines.bndrun")
.excludeExport("org.junit*")
.excludeExport("junit*");
this.builder = builder;
setTmpDir();
TestRunData result = runTestsEclipse(JUnit5AbortTest.class, JUnit4AbortTest.class);
assertThat(result).hasErroredTest("Initialization Error",
new JUnitException("Couldn't find any registered TestEngines"));
}
}
@Test
public void eclipseListener_handlesNoJUnit3Gracefully() throws Exception {
builder.excludeExport("junit.framework");
Class<?>[] tests = {
JUnit4ComparisonTest.class, JUnit5Test.class, JUnit5SimpleComparisonTest.class
};
TestRunData result = runTestsEclipse(tests);
assertThat(result).as("result")
.hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class,
"expected", "actual");
TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure"));
assertThat(f).as("emptyComparisonFailure")
.isNotNull();
if (f != null) {
assertThat(f.status).as("emptyComparisonFailure:status")
.isEqualTo(STATUS_FAILURE);
assertThat(f.expected).as("emptyComparisonFailure:expected")
.isNull();
assertThat(f.actual).as("emptyComparisonFailure:actual")
.isNull();
}
}
@Test
public void eclipseListener_handlesNoJUnit4Gracefully() throws Exception {
try (LaunchpadBuilder builder = new LaunchpadBuilder()) {
IO.close(this.builder);
builder.debug();
builder.bndrun("no-vintage-engine.bndrun")
.excludeExport("aQute.tester.bundle.*")
.excludeExport("org.junit*")
.excludeExport("junit*");
this.builder = builder;
setTmpDir();
Class<?>[] tests = {
JUnit3ComparisonTest.class, JUnit5Test.class, JUnit5SimpleComparisonTest.class
};
TestRunData result = runTestsEclipse(tests);
assertThat(result).as("result")
.hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class,
"expected", "actual");
TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure"));
assertThat(f).as("emptyComparisonFailure")
.isNotNull();
if (f != null) {
assertThat(f.status).as("emptyComparisonFailure:status")
.isEqualTo(STATUS_FAILURE);
assertThat(f.expected).as("emptyComparisonFailure:expected")
.isNull();
assertThat(f.actual).as("emptyComparisonFailure:actual")
.isNull();
}
}
}
@Test
public void testerUnresolvedTrue_isPassedThroughToBundleEngine() {
builder.set(TESTER_UNRESOLVED, "true");
AtomicReference<Bundle> bundleRef = new AtomicReference<>();
TestRunData result = runTestsEclipse(() -> {
bundleRef.set(bundle().importPackage("some.unknown.package")
.install());
}, JUnit3Test.class, JUnit4Test.class);
assertThat(result).hasSuccessfulTest("Unresolved bundles");
}
@Test
public void testerUnresolvedFalse_isPassedThroughToBundleEngine() {
builder.set(TESTER_UNRESOLVED, "false");
AtomicReference<Bundle> bundleRef = new AtomicReference<>();
TestRunData result = runTestsEclipse(() -> {
bundleRef.set(bundle().importPackage("some.unknown.package")
.install());
}, JUnit3Test.class, JUnit4Test.class);
assertThat(result.getNameMap()
.get("Unresolved bundles")).isNull();
}
@Test
public void testerNames_withParameters_isHonouredByTester() {
builder.set(TESTER_NAMES,
"'" + ParameterizedTesterNamesTest.class.getName() + ":parameterizedMethod(java.lang.String,float)'");
runTests(0, JUnit3Test.class, JUnit4Test.class, ParameterizedTesterNamesTest.class);
assertThat(testBundler.getCurrentThread(JUnit3Test.class)).as("JUnit3 thread")
.isNull();
assertThat(testBundler.getCurrentThread(JUnit4Test.class)).as("JUnit4 thread")
.isNull();
assertThat(testBundler.getInteger("countParameterized", ParameterizedTesterNamesTest.class))
.as("parameterizedMethod")
.isEqualTo(5);
assertThat(testBundler.getInteger("countOther", ParameterizedTesterNamesTest.class)).as("countOther")
.isEqualTo(0);
}
@Test
public void xmlReporter_generatesCompleteXmlFile() throws Exception {
final ExitCode exitCode = runTests(JUnit3Test.class, With1Error1Failure.class, With2Failures.class);
final String fileName = "TEST-" + testBundle.getSymbolicName() + "-" + testBundle.getVersion() + ".xml";
File xmlFile = new File(getTmpDir(), fileName);
Assertions.assertThat(xmlFile)
.as("xmlFile")
.exists();
AtomicReference<Document> docContainer = new AtomicReference<>();
Assertions.assertThatCode(() -> {
DocumentBuilderFactory dbFactory = XML.newDocumentBuilderFactory();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
docContainer.set(dBuilder.parse(xmlFile));
})
.doesNotThrowAnyException();
Document doc = docContainer.get();
XmlAssert.assertThat(doc)
.nodesByXPath("/testsuite")
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testSuite() + "/testcase")
.hasSize(7);
XmlAssert.assertThat(doc)
.nodesByXPath(testCase(JUnit3Test.class, "testSomething"))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseError(With1Error1Failure.class, "test1", RuntimeException.class))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCase(With1Error1Failure.class, "test2"))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseFailure(With1Error1Failure.class, "test3", AssertionError.class))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseFailure(With2Failures.class, "test1", AssertionError.class))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCase(With2Failures.class, "test2"))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseFailure(With2Failures.class, "test3", CustomAssertionError.class))
.hasSize(1);
}
// Unlike JUnit 4, Jupiter skips the tests when the parent container
// fails and does not report the children as test failures.
@Test
public void exitCode_countsJupiterContainerErrorsAndFailures() {
runTests(2, JUnit5ContainerFailure.class, JUnit5ContainerError.class);
}
}
| garydgregory/bnd | biz.aQute.tester.test/test/aQute/tester/junit/platform/test/ActivatorJUnitPlatformTest.java |
45,861 | /**
* Copyright (C) 2013-2020 Vasilis Vryniotis <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datumbox.framework.core.common.text;
import com.datumbox.framework.tests.abstracts.AbstractTest;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Test cases for StringCleaner.
*
* @author Vasilis Vryniotis <[email protected]>
*/
public class StringCleanerTest extends AbstractTest {
/**
* Test of tokenizeURLs method, of class StringCleaner.
*/
@Test
public void testTokenizeURLs() {
logger.info("tokenizeURLs");
String text = "Test, test δοκιμή http://wWw.Google.com/page?query=1#hash test test";
String expResult = "Test, test δοκιμή PREPROCESSDOC_URL test test";
String result = StringCleaner.tokenizeURLs(text);
assertEquals(expResult, result);
}
/**
* Test of tokenizeSmileys method, of class StringCleaner.
*/
@Test
public void testTokenizeSmileys() {
logger.info("tokenizeSmileys");
String text = "Test, test δοκιμή :) :( :] :[ test test";
String expResult = "Test, test δοκιμή PREPROCESSDOC_EM1 PREPROCESSDOC_EM3 PREPROCESSDOC_EM8 PREPROCESSDOC_EM9 test test";
String result = StringCleaner.tokenizeSmileys(text);
assertEquals(expResult, result);
}
/**
* Test of removeExtraSpaces method, of class StringCleaner.
*/
@Test
public void testRemoveExtraSpaces() {
logger.info("removeExtraSpaces");
String text = " test test test test test\n\n\n\r\n\r\r test\n";
String expResult = "test test test test test test";
String result = StringCleaner.removeExtraSpaces(text);
assertEquals(expResult, result);
}
/**
* Test of removeSymbols method, of class StringCleaner.
*/
@Test
public void testRemoveSymbols() {
logger.info("removeSymbols");
String text = "test ` ~ ! @ # $ % ^ & * ( ) _ - + = < , > . ? / \" ' : ; [ { } ] | \\ test `~!@#$%^&*()_-+=<,>.?/\\\"':;[{}]|\\\\ test";
String expResult = "test _ test _ test";
String result = StringCleaner.removeExtraSpaces(StringCleaner.removeSymbols(text));
assertEquals(expResult, result);
}
/**
* Test of unifyTerminators method, of class StringCleaner.
*/
@Test
public void testUnifyTerminators() {
logger.info("unifyTerminators");
String text = " This is amazing!!! ! How is this possible?!?!?!?!!!???! ";
String expResult = "This is amazing. How is this possible.";
String result = StringCleaner.unifyTerminators(text);
assertEquals(expResult, result);
}
/**
* Test of removeAccents method, of class StringCleaner.
*/
@Test
public void testRemoveAccents() {
logger.info("removeAccents");
String text = "'ά','ό','έ','ί','ϊ','ΐ','ή','ύ','ϋ','ΰ','ώ','à','á','â','ã','ä','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ù','ú','û','ü','ý','ÿ','Ά','Ό','Έ','Ί','Ϊ','Ή','Ύ','Ϋ','Ώ','À','Á','Â','Ã','Ä','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ñ','Ò','Ó','Ô','Õ','Ö','Ù','Ú','Û','Ü','Ý'";
String expResult = "'α','ο','ε','ι','ι','ι','η','υ','υ','υ','ω','a','a','a','a','a','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','u','u','u','u','y','y','Α','Ο','Ε','Ι','Ι','Η','Υ','Υ','Ω','A','A','A','A','A','C','E','E','E','E','I','I','I','I','N','O','O','O','O','O','U','U','U','U','Y'";
String result = StringCleaner.removeAccents(text);
assertEquals(expResult, result);
}
}
| datumbox/datumbox-framework | datumbox-framework-core/src/test/java/com/datumbox/framework/core/common/text/StringCleanerTest.java |
45,862 | package com.github.tminglei.bind;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import com.github.tminglei.bind.spi.*;
import static org.testng.Assert.*;
import static com.github.tminglei.bind.FrameworkUtils.*;
import static com.github.tminglei.bind.Utils.*;
public class ConstraintsTest {
private ResourceBundle bundle = ResourceBundle.getBundle("bind-messages");
private Messages messages = (key) -> bundle.getString(key);
@BeforeClass
public void start() {
System.out.println(cyan("test pre-defined constraints"));
}
// required test
@Test
public void testRequired_SingleInput() {
System.out.println(green(">> required - single input"));
Constraint required = Constraints.required();
assertEquals(required.apply("", newmap(entry("", null)), messages, new Options()._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'' is required")));
assertEquals(required.apply("", newmap(entry("", "")), messages, new Options()._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'' is required")));
assertEquals(required.apply("", newmap(entry("", "test")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
}
@Test
public void testRequired_MultiInput() {
System.out.println(green(">> required - multiple inputs"));
Constraint required = Constraints.required("%s is required");
assertEquals(required.apply("tt", newmap(entry("tt.a", "tt")), messages, new Options()._label("haha")._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt.a", null)), messages, new Options()._label("haha")._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt", null)), messages, new Options()._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("tt", "tt is required")));
assertEquals(required.apply("tt", newmap(), messages, new Options()._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("tt", "tt is required")));
}
@Test
public void testRequired_PloyInput() {
System.out.println(green(">> required - polymorphic input"));
Constraint required = Constraints.required("%s is required");
assertEquals(required.apply("tt", newmap(entry("tt.a", "tt")), messages, new Options()._label("haha")._inputMode(InputMode.POLYMORPHIC)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt.a", null)), messages, new Options()._label("haha")._inputMode(InputMode.POLYMORPHIC)),
Collections.EMPTY_LIST);
assertEquals(required.apply("tt", newmap(entry("tt", null)), messages, new Options()._inputMode(InputMode.POLYMORPHIC)),
Arrays.asList(entry("tt", "tt is required")));
assertEquals(required.apply("tt.a", newmap(entry("tt.a", null)), messages, new Options()._inputMode(InputMode.POLYMORPHIC)),
Arrays.asList(entry("tt.a", "a is required")));
}
// max length test
@Test
public void testMaxLength_SimpleUse() {
System.out.println(green(">> max length - simple use"));
Constraint maxlength = Constraints.maxLength(10);
assertEquals(maxlength.apply("", newmap(entry("", "wetyyuu")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(maxlength.apply("", newmap(entry("", "wetyettyiiie")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'wetyettyiiie' must be shorter than 10 characters (include boundary: true)")));
assertEquals(maxlength.apply("", newmap(entry("", "tuewerri97")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
}
@Test
public void testMaxLength_WithCustomMessage() {
System.out.println(green(">> max length - with custom message"));
Constraint maxlength = Constraints.maxLength(10, "'%s': length > %d");
assertEquals(maxlength.apply("", newmap(entry("", "eewryuooerjhy")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'eewryuooerjhy': length > 10")));
}
// min length test
@Test
public void testMinLength_SimpleUse() {
System.out.println(green(">> min length - simple use"));
Constraint minlength = Constraints.minLength(3);
assertEquals(minlength.apply("", newmap(entry("", "er")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'er' must be longer than 3 characters (include boundary: true)")));
assertEquals(minlength.apply("", newmap(entry("", "ert6")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(minlength.apply("", newmap(entry("", "tee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
}
@Test
public void testMinLength_WithoutBoundary() {
System.out.println(green(">> min length - w/o boundary"));
Constraint minlength = Constraints.minLength(3, false);
assertEquals(minlength.apply("", newmap(entry("", "er")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'er' must be longer than 3 characters (include boundary: false)")));
assertEquals(minlength.apply("", newmap(entry("", "ert6")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(minlength.apply("", newmap(entry("", "tee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'tee' must be longer than 3 characters (include boundary: false)")));
}
@Test
public void testMinLength_WithCustomMessage() {
System.out.println(green(">> min length - custom message"));
Constraint minlength = Constraints.minLength(3, "'%s': length cannot < %d");
assertEquals(minlength.apply("", newmap(entry("", "te")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'te': length cannot < 3")));
}
// length test
@Test
public void testLength_SimpleUse() {
System.out.println(green(">> length - simple use"));
Constraint length = Constraints.length(9);
assertEquals(length.apply("", newmap(entry("", "123456789")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(length.apply("", newmap(entry("", "123")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'123' must be 9 characters")));
assertEquals(length.apply("", newmap(entry("", "1234567890")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'1234567890' must be 9 characters")));
}
@Test
public void testLength_WithCustomMessage() {
System.out.println(green(">> length - with custom message"));
Constraint length = Constraints.length(9, "'%s': length not equals to %d");
assertEquals(length.apply("", newmap(entry("", "123")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'123': length not equals to 9")));
}
// oneOf test
@Test
public void testOneOf_SimpleUse() {
System.out.println(green(">> one of - simple use"));
Constraint oneof = Constraints.oneOf(Arrays.asList("a", "b", "c"));
assertEquals(oneof.apply("", newmap(entry("", "a")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(oneof.apply("", newmap(entry("", "t")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'t' must be one of [a, b, c]")));
assertEquals(oneof.apply("", newmap(entry("", null)), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'null' must be one of [a, b, c]")));
}
@Test
public void testOneOf_WithCustomMessage() {
System.out.println(green(">> one of - with custom message"));
Constraint oneof = Constraints.oneOf(Arrays.asList("a", "b", "c"), "'%s': is not one of %s");
assertEquals(oneof.apply("t.a", newmap(entry("t.a", "ts")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("t.a", "'ts': is not one of [a, b, c]")));
}
// pattern test
@Test
public void testPattern_SimpleUse() {
System.out.println(green(">> pattern - simple use"));
Constraint pattern = Constraints.pattern("^(\\d+)$");
assertEquals(pattern.apply("", newmap(entry("", "1234657")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(pattern.apply("", newmap(entry("", "32566y")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'32566y' must be '^(\\d+)$'")));
assertEquals(pattern.apply("", newmap(entry("", "123,567")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'123,567' must be '^(\\d+)$'")));
}
@Test
public void testPattern_WithCustomMessage() {
System.out.println(green(">> pattern - with custom message"));
Constraint pattern = Constraints.pattern("^(\\d+)$", "'%s' not match '%s'");
assertEquals(pattern.apply("", newmap(entry("", "t4366")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'t4366' not match '^(\\d+)$'")));
}
// patternNot test
@Test
public void testPatternNot_SimpleUse() {
System.out.println(green(">> pattern not - simple use"));
Constraint patternNot = Constraints.patternNot(".*\\[(\\d*[^\\d\\[\\]]+\\d*)+\\].*");
assertEquals(patternNot.apply("", newmap(entry("", "eree.[1234657].eee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
assertEquals(patternNot.apply("", newmap(entry("", "errr.[32566y].ereee")), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'errr.[32566y].ereee' mustn't be '.*\\[(\\d*[^\\d\\[\\]]+\\d*)+\\].*'")));
}
@Test
public void testPatternNot_WithCustomMessage() {
System.out.println(green(">> pattern not - with custom message"));
Constraint patternNot = Constraints.pattern("^(\\d+)$", "'%s' contains illegal array index");
assertEquals(patternNot.apply("", newmap(entry("", "ewtr.[t4366].eweee")), messages, new Options()._label("haha")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'ewtr.[t4366].eweee' contains illegal array index")));
}
// email test
/**
* test cases copied from:
* http://en.wikipedia.org/wiki/Email_address
*/
@Test
public void testEmail_ValidEmailAddresses() {
System.out.println(green(">> email - valid email addresses"));
Constraint email = Constraints.email("'%s' not valid");
Arrays.asList(
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"//,
// "user@localserver",
// internationalization examples
// "Pelé@example.com", //Latin Alphabet (with diacritics)
// "δοκιμή@παράδειγμα.δοκιμή", //Greek Alphabet
// "我買@屋企.香港", //Traditional Chinese Characters
// "甲斐@黒川.日本", //Japanese Characters
// "чебурашка@ящик-с-апельсинами.рф" //Cyrillic Characters
).stream().forEach(emailAddr -> {
assertEquals(email.apply("", newmap(entry("", emailAddr)), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Collections.EMPTY_LIST);
});
}
@Test
public void testEmail_InvalidEmailAddresses() {
System.out.println(green(">> email - invalid email addresses"));
Constraint email = Constraints.email();
Arrays.asList(
"Abc.example.com", //(an @ character must separate the local and domain parts)
"A@b@[email protected]", //(only one @ is allowed outside quotation marks)
"a\"b(c)d,e:f;g<h>i[j\\k][email protected]", //(none of the special characters in this local part is allowed outside quotation marks)
"just\"not\"[email protected]", //(quoted strings must be dot separated or the only element making up the local-part)
"this is\"not\\[email protected]", //(spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a backslash)
"this\\ still\\\"not\\\\[email protected]", //(even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes)
"[email protected]", //(double dot before @)
"[email protected]" //(double dot after @)
).stream().forEach(emailAddr -> {
assertEquals(email.apply("", newmap(entry("", emailAddr)), messages, new Options()._label("")._inputMode(InputMode.SINGLE)),
Arrays.asList(entry("", "'" + emailAddr + "' is not a valid email")));
});
}
// indexInKeys test
@Test
public void testIndexInKey_SimpleUse() {
System.out.println(green(">> index in key - simple use"));
Constraint index = Constraints.indexInKeys();
assertEquals(index.apply("a", newmap(entry("a[0]", "aaa")), messages, new Options()._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(index.apply("a", newmap(entry("a[t0]", "aaa"), entry("a[3]", "tew")), messages, new Options()._label("")._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("a[t0]", "'a[t0]' contains illegal array index")));
assertEquals(index.apply("a", newmap(entry("a[t1]", "aewr"), entry("a[t4]", "ewre")), messages,
new Options()._label("xx")._inputMode(InputMode.MULTIPLE)).stream().collect(Collectors.toSet()),
Arrays.asList(entry("a[t1]", "'a[t1]' contains illegal array index"), entry("a[t4]", "'a[t4]' contains illegal array index"))
.stream().collect(Collectors.toSet()));
}
@Test
public void testIndexInKey_WithCustomMessage() {
System.out.println(green(">> index in key - with custom message"));
Constraint index = Constraints.indexInKeys("illegal array index (%s)");
assertEquals(index.apply("a", newmap(entry("a[0]", "aaa")), messages, new Options()._label("xx")._inputMode(InputMode.MULTIPLE)),
Collections.EMPTY_LIST);
assertEquals(index.apply("a", newmap(entry("a[t0]", "aaa"), entry("a[3]", "tew")), messages, new Options()._label("")._inputMode(InputMode.MULTIPLE)),
Arrays.asList(entry("a[t0]", "illegal array index (a[t0])")));
assertEquals(index.apply("", newmap(entry("a[t1]", "aewr"), entry("a[t4].er", "ewre")), messages,
new Options()._label("xx")._inputMode(InputMode.MULTIPLE)).stream().collect(Collectors.toSet()),
Arrays.asList(entry("a[t1]", "illegal array index (a[t1])"), entry("a[t4].er", "illegal array index (a[t4].er)"))
.stream().collect(Collectors.toSet()));
}
}
| tminglei/form-binder-java | src/test/java/com/github/tminglei/bind/ConstraintsTest.java |
45,863 | package regex.email;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class EmailValidatorUnicodeTest {
@ParameterizedTest(name = "#{index} - Run test with email = {0}")
@MethodSource("validEmailProvider")
void test_email_valid(String email) {
assertTrue(EmailValidatorUnicode.isValid(email));
}
// Valid email addresses
static Stream<String> validEmailProvider() {
return Stream.of(
"[email protected]", // simple
"[email protected]", // .co.uk, 2 tld
"[email protected]", // -
"[email protected]", // .
"[email protected]", // _
"[email protected]", // local-part one letter
"[email protected]", // domain contains a hyphen -
"[email protected]", // domain contains two hyphens - -
"[email protected]", // domain contains . -
"[email protected]", // local part contains . -
"我買@屋企.香港", // chinese characters
"二ノ宮@黒川.日本", // Japanese characters
"δοκιμή@παράδειγμα.δοκιμή"); // Greek alphabet
}
}
| vinkrish/DataStructure-Algorithm-Snippets_Java | src/test/java/regex/email/EmailValidatorUnicodeTest.java |
45,864 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import org.junit.Test;
import static org.junit.Assert.*;
public class SocksCmdRequestTest {
@Test
public void testConstructorParamsAreNotNull(){
try {
new SocksCmdRequest(null, SocksAddressType.UNKNOWN, "", 0);
} catch (Exception e){
assertTrue(e instanceof NullPointerException);
}
try {
new SocksCmdRequest(SocksCmdType.UNKNOWN, null, "", 0);
} catch (Exception e){
assertTrue(e instanceof NullPointerException);
}
try {
new SocksCmdRequest(SocksCmdType.UNKNOWN, SocksAddressType.UNKNOWN, null, 0);
} catch (Exception e){
assertTrue(e instanceof NullPointerException);
}
}
@Test
public void testIPv4CorrectAddress(){
try {
new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv4, "54.54.1111.253", 0);
} catch (Exception e){
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testIPv6CorrectAddress(){
try {
new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.IPv6, "xxx:xxx:xxx", 0);
} catch (Exception e){
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testIDNNotExceeds255CharsLimit(){
try {
new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN,
"παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" +
"παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" +
"παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" +
"παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 0);
} catch (Exception e){
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testValidPortRange(){
try {
new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN,
"παράδειγμα.δοκιμήπαράδει", -1);
} catch (Exception e){
assertTrue(e instanceof IllegalArgumentException);
}
try {
new SocksCmdRequest(SocksCmdType.BIND, SocksAddressType.DOMAIN,
"παράδειγμα.δοκιμήπαράδει", 65536);
} catch (Exception e){
assertTrue(e instanceof IllegalArgumentException);
}
}
}
| hgschmie/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestTest.java |
45,865 | /*
* Copyright 2021 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.contrib.handler.codec.socksx.v5;
import io.netty5.channel.embedded.EmbeddedChannel;
import io.netty5.util.NetUtil;
import io.netty5.util.internal.SocketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.junit.jupiter.api.Test;
import java.net.IDN;
import java.net.UnknownHostException;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
public class Socks5CommandRequestDecoderTest {
private static final Logger logger =
LoggerFactory.getLogger(Socks5CommandRequestDecoderTest.class);
private static void test(
Socks5CommandType type, Socks5AddressType dstAddrType, String dstAddr, int dstPort) {
logger.debug(
"Testing type: " + type + " dstAddrType: " + dstAddrType +
" dstAddr: " + dstAddr + " dstPort: " + dstPort);
Socks5CommandRequest msg =
new DefaultSocks5CommandRequest(type, dstAddrType, dstAddr, dstPort);
EmbeddedChannel embedder = new EmbeddedChannel(new Socks5CommandRequestDecoder());
Socks5CommonTestUtils.writeFromClientToServer(embedder, msg);
msg = embedder.readInbound();
assertSame(msg.type(), type);
assertSame(msg.dstAddrType(), dstAddrType);
assertEquals(msg.dstAddr(), IDN.toASCII(dstAddr));
assertEquals(msg.dstPort(), dstPort);
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1", };
int[] ports = {1, 32769, 65535 };
for (Socks5CommandType cmdType: Arrays.asList(Socks5CommandType.BIND,
Socks5CommandType.CONNECT,
Socks5CommandType.UDP_ASSOCIATE)) {
for (String host : hosts) {
for (int port : ports) {
test(cmdType, Socks5AddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() throws UnknownHostException {
String[] hosts = {
NetUtil.bytesToIpAddress(SocketUtils.addressByName("::1").getAddress()) };
int[] ports = {1, 32769, 65535};
for (Socks5CommandType cmdType: Arrays.asList(Socks5CommandType.BIND,
Socks5CommandType.CONNECT,
Socks5CommandType.UDP_ASSOCIATE)) {
for (String host : hosts) {
for (int port : ports) {
test(cmdType, Socks5AddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {1, 32769, 65535};
for (Socks5CommandType cmdType: Arrays.asList(Socks5CommandType.BIND,
Socks5CommandType.CONNECT,
Socks5CommandType.UDP_ASSOCIATE)) {
for (String host : hosts) {
for (int port : ports) {
test(cmdType, Socks5AddressType.DOMAIN, host, port);
}
}
}
}
}
| netty-contrib/socks-proxy | codec-socks/src/test/java/io/netty/contrib/handler/codec/socksx/v5/Socks5CommandRequestDecoderTest.java |
45,867 | package com.tendcloud.tenddata;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* compiled from: td */
/* loaded from: classes2.dex */
public class n {
private static final String A = "(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w)";
private static final String B = "(?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))";
private static final String C = "(?:(?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
private static final String D = "(?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
private static final String E = "((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))";
private static final String F = "((?:\\b|$|^)(?:(?:(?i:http|https|rtsp|ws|wss)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))";
private static final String G = "a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]\\+\\-_%'";
private static final String H = "[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]\\+\\-_%'](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]\\+\\-_%'\\.]{1,62}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]\\+\\-_%'])?";
private static final String I = "(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]{2,63})";
@Deprecated
/* renamed from: c reason: collision with root package name */
public static final String f22970c = "(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))";
/* renamed from: d reason: collision with root package name */
static final String f22971d = "(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))";
@Deprecated
/* renamed from: e reason: collision with root package name */
public static final String f22972e = "a-zA-Z0-9 -\ud7ff豈-\ufdcfﷰ-\uffef";
/* renamed from: n reason: collision with root package name */
private static final String f22981n = "[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]";
/* renamed from: o reason: collision with root package name */
private static final String f22982o = "a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]";
/* renamed from: p reason: collision with root package name */
private static final String f22983p = "a-zA-Z[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]";
/* renamed from: q reason: collision with root package name */
private static final String f22984q = "[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}";
/* renamed from: r reason: collision with root package name */
private static final String f22985r = "xn\\-\\-[\\w\\-]{0,58}\\w";
/* renamed from: s reason: collision with root package name */
private static final String f22986s = "(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]{2,63})";
/* renamed from: t reason: collision with root package name */
private static final String f22987t = "([a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]{2,63})";
/* renamed from: v reason: collision with root package name */
private static final String f22989v = "(?i:http|https|rtsp|ws|wss)://";
/* renamed from: w reason: collision with root package name */
private static final String f22990w = "(?:\\b|$|^)";
/* renamed from: x reason: collision with root package name */
private static final String f22991x = "(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@";
/* renamed from: y reason: collision with root package name */
private static final String f22992y = "\\:\\d{1,5}";
/* renamed from: z reason: collision with root package name */
private static final String f22993z = "[/\\?](?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*";
@Deprecated
/* renamed from: a reason: collision with root package name */
public static final String f22968a = "((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw])";
@Deprecated
/* renamed from: b reason: collision with root package name */
public static final Pattern f22969b = Pattern.compile(f22968a);
/* renamed from: m reason: collision with root package name */
private static final String f22980m = "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))";
/* renamed from: f reason: collision with root package name */
public static final Pattern f22973f = Pattern.compile(f22980m);
/* renamed from: u reason: collision with root package name */
private static final String f22988u = "(([a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
/* renamed from: g reason: collision with root package name */
public static final Pattern f22974g = Pattern.compile(f22988u);
/* renamed from: h reason: collision with root package name */
public static final Pattern f22975h = Pattern.compile("(((?:(?i:http|https|rtsp|ws|wss)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(([a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)([/\\?](?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))");
/* renamed from: i reason: collision with root package name */
public static final Pattern f22976i = Pattern.compile("(((?:\\b|$|^)(?:(?:(?i:http|https|rtsp|ws|wss)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))|((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^)))");
/* renamed from: j reason: collision with root package name */
public static final Pattern f22977j = Pattern.compile("((?:\\b|$|^)(?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]\\+\\-_%'](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]\\+\\-_%'\\.]{1,62}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]\\+\\-_%'])?@(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]](?:[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]_\\-]{0,61}[a-zA-Z0-9[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -\ud7ff豈-\ufdcfﷰ-\uffef𐀀-\u1fffd𠀀-\u2fffd\u30000-\u3fffd\u40000-\u4fffd\u50000-\u5fffd\u60000-\u6fffd\u70000-\u7fffd\u80000-\u8fffd\u90000-\u9fffd\ua0000-\uafffd\ub0000-\ubfffd\uc0000-\ucfffd\ud0000-\udfffd\ue1000-\uefffd&&[^ [\u2000-\u200a]\u2028\u2029 \u3000]]]{2,63}))(?:\\b|$|^))");
/* renamed from: k reason: collision with root package name */
public static final Pattern f22978k = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+");
/* renamed from: l reason: collision with root package name */
public static final Pattern f22979l = Pattern.compile("(\\+[0-9]+[\\- \\.]*)?(\\([0-9]+\\)[\\- \\.]*)?([0-9][0-9\\- \\.]+[0-9])");
private n() {
}
public static final String a(Matcher matcher) {
StringBuilder sb2 = new StringBuilder();
int groupCount = matcher.groupCount();
for (int i10 = 1; i10 <= groupCount; i10++) {
String group = matcher.group(i10);
if (group != null) {
sb2.append(group);
}
}
return sb2.toString();
}
public static final String b(Matcher matcher) {
StringBuilder sb2 = new StringBuilder();
String group = matcher.group();
int length = group.length();
for (int i10 = 0; i10 < length; i10++) {
char charAt = group.charAt(i10);
if (charAt == '+' || Character.isDigit(charAt)) {
sb2.append(charAt);
}
}
return sb2.toString();
}
}
| coolman6942o/mobvoi_app_v2 | 3ce0c1933de267f685ec49d27325ffec-java/com/tendcloud/tenddata/n.java |
45,868 | package com.araguaneybits.core.wallet;
import com.araguaneybits.core.coins.BitcoinMain;
import com.araguaneybits.core.coins.CoinType;
import com.araguaneybits.core.coins.DogecoinTest;
import com.araguaneybits.core.coins.NuBitsMain;
import com.araguaneybits.core.coins.Value;
import com.araguaneybits.core.coins.VpncoinMain;
import com.araguaneybits.core.exceptions.AddressMalformedException;
import com.araguaneybits.core.exceptions.Bip44KeyLookAheadExceededException;
import com.araguaneybits.core.exceptions.KeyIsEncryptedException;
import com.araguaneybits.core.exceptions.MissingPrivateKeyException;
import com.araguaneybits.core.network.AddressStatus;
import com.araguaneybits.core.network.BlockHeader;
import com.araguaneybits.core.network.ServerClient.HistoryTx;
import com.araguaneybits.core.network.ServerClient.UnspentTx;
import com.araguaneybits.core.network.interfaces.ConnectionEventListener;
import com.araguaneybits.core.network.interfaces.TransactionEventListener;
import com.araguaneybits.core.protos.Protos;
import com.araguaneybits.core.wallet.families.bitcoin.BitAddress;
import com.araguaneybits.core.wallet.families.bitcoin.BitBlockchainConnection;
import com.araguaneybits.core.wallet.families.bitcoin.BitSendRequest;
import com.araguaneybits.core.wallet.families.bitcoin.BitTransaction;
import com.araguaneybits.core.wallet.families.bitcoin.BitTransactionEventListener;
import com.araguaneybits.core.wallet.families.bitcoin.OutPointOutput;
import com.araguaneybits.core.wallet.families.bitcoin.TrimmedOutPoint;
import com.google.common.collect.ImmutableList;
import org.bitcoinj.core.ChildMessage;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence.Source;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.core.Utils;
import org.bitcoinj.crypto.DeterministicHierarchy;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.crypto.KeyCrypter;
import org.bitcoinj.crypto.KeyCrypterScrypt;
import org.bitcoinj.store.UnreadableWalletException;
import org.bitcoinj.utils.BriefLogFormatter;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bitcoinj.wallet.KeyChain;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.spongycastle.crypto.params.KeyParameter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.araguaneybits.core.Preconditions.checkNotNull;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author John L. Jegutanis
*/
public class WalletPocketHDTest {
static final CoinType BTC = BitcoinMain.get();
static final CoinType DOGE = DogecoinTest.get();
static final CoinType NBT = NuBitsMain.get();
static final CoinType VPN = VpncoinMain.get();
static final List<String> MNEMONIC = ImmutableList.of("citizen", "fever", "scale", "nurse", "brief", "round", "ski", "fiction", "car", "fitness", "pluck", "act");
static final byte[] AES_KEY_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7};
static final long AMOUNT_TO_SEND = 2700000000L;
static final String MESSAGE = "test";
static final String MESSAGE_UNICODE = "δοκιμή испытание 测试";
static final String EXPECTED_BITCOIN_SIG = "IMBbIFDDuUwomYlvSjwWytqP/CXYym2yOKbJUx8Y+ujzZKBwoCFMr73GUxpr1Ird/DvnNZcsQLphvx18ftqN54o=";
static final String EXPECTED_BITCOIN_SIG_UNICODE = "IGGZEOBsVny5dozTOfc2/3UuvmZGdDI4XK/03HIk34PILd2oXbnq+87GINT3lumeXcgSO2NkGzUFcQ1SCSVI3Hk=";
static final String EXPECTED_NUBITS_SIG = "IMuzNZTZIjZjLicyDFGzqFl21vqNBGW1N5m4qHBRqbTvLBbkQeGjraeLmZEt7mRH4MSMPLFXW2T3Maz+HYx1tEc=";
static final String EXPECTED_NUBITS_SIG_UNICODE = "Hx7xkBbboXrp96dbQrJFzm2unTGwLstjbWlKa1/N1E4LJqbwJAJR1qIvwXm6LHQFnLOzwoQA45zYNjwUEPMc8sg=";
DeterministicSeed seed = new DeterministicSeed(MNEMONIC, null, "", 0);
DeterministicKey masterKey = HDKeyDerivation.createMasterPrivateKey(checkNotNull(seed.getSeedBytes()));
DeterministicHierarchy hierarchy = new DeterministicHierarchy(masterKey);
DeterministicKey rootKey = hierarchy.get(DOGE.getBip44Path(0), false, true);
KeyParameter aesKey = new KeyParameter(AES_KEY_BYTES);
KeyCrypter crypter = new KeyCrypterScrypt();
WalletPocketHD pocket;
@Before
public void setup() {
BriefLogFormatter.init();
pocket = new WalletPocketHD(rootKey, DOGE, null, null);
pocket.keys.setLookaheadSize(20);
}
@Test
public void testId() throws Exception {
assertEquals("8747886e9a77fe2a1588df3168b867648434d6d339b0b448793ae1db8f283f41", pocket.getId());
}
@Test
public void testSingleAddressWallet() throws Exception {
ECKey key = pocket.keys.getCurrentUnusedKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
BitWalletSingleKey bitWalletSingleKey = new BitWalletSingleKey(DOGE, key);
bitWalletSingleKey.onConnection(getBlockchainConnection(DOGE));
assertEquals(DOGE.value("10"), bitWalletSingleKey.getBalance());
}
@Test
public void xpubWallet() {
String xpub = "xpub67tVq9TLPPoaHVSiYu8mqahm3eztTPUts6JUftNq3pZF1PJwjknrTqQhjc2qRGd6vS8wANu7mLnqkiUzFZ1xZsAZoUMi8o6icMhzGCAhcSW";
DeterministicKey key = DeterministicKey.deserializeB58(null, xpub);
WalletPocketHD account = new WalletPocketHD(key, BTC, null, null);
assertEquals("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", account.getReceiveAddress().toString());
account = new WalletPocketHD(key, NBT, null, null);
assertEquals("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", account.getReceiveAddress().toString());
}
@Test
public void xpubWalletSerialized() throws Exception {
WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null);
Protos.WalletPocket proto = account.toProtobuf();
WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null);
assertEquals(account.getPublicKeySerialized(), newAccount.getPublicKeySerialized());
}
@Test
public void signMessage() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException {
WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature());
signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature());
pocketHD = new WalletPocketHD(rootKey, NBT, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_NUBITS_SIG, signedMessage.getSignature());
signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE_UNICODE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_NUBITS_SIG_UNICODE, signedMessage.getSignature());
}
@Test
public void signMessageEncrypted() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException {
WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
pocketHD.encrypt(crypter, aesKey);
SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE);
pocketHD.signMessage(signedMessage, aesKey);
assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature());
signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE);
pocketHD.signMessage(signedMessage, aesKey);
assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature());
}
@Test
public void signMessageEncryptedFailed() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException {
WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
pocketHD.encrypt(crypter, aesKey);
SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE);
pocketHD.signMessage(signedMessage, null);
assertEquals(SignedMessage.Status.KeyIsEncrypted, signedMessage.status);
}
@Test
public void watchingAddresses() {
List<AbstractAddress> watchingAddresses = pocket.getAddressesToWatch();
assertEquals(40, watchingAddresses.size()); // 20 + 20 lookahead size
for (int i = 0; i < addresses.size(); i++) {
assertEquals(addresses.get(i), watchingAddresses.get(i).toString());
}
}
@Test
public void issuedKeys() throws Bip44KeyLookAheadExceededException {
List<BitAddress> issuedAddresses = new ArrayList<>();
assertEquals(0, pocket.getIssuedReceiveAddresses().size());
assertEquals(0, pocket.keys.getNumIssuedExternalKeys());
issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
BitAddress freshAddress = pocket.getFreshReceiveAddress();
assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
assertEquals(1, pocket.getIssuedReceiveAddresses().size());
assertEquals(1, pocket.keys.getNumIssuedExternalKeys());
assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses());
issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
freshAddress = pocket.getFreshReceiveAddress();
assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
assertEquals(2, pocket.getIssuedReceiveAddresses().size());
assertEquals(2, pocket.keys.getNumIssuedExternalKeys());
assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses());
}
@Test
public void issuedKeysLimit() throws Exception {
assertTrue(pocket.canCreateFreshReceiveAddress());
try {
for (int i = 0; i < 100; i++) {
pocket.getFreshReceiveAddress();
}
} catch (Bip44KeyLookAheadExceededException e) {
assertFalse(pocket.canCreateFreshReceiveAddress());
// We haven't used any key so the total must be 20 - 1 (the unused key)
assertEquals(19, pocket.getNumberIssuedReceiveAddresses());
assertEquals(19, pocket.getIssuedReceiveAddresses().size());
}
pocket.onConnection(getBlockchainConnection(DOGE));
assertTrue(pocket.canCreateFreshReceiveAddress());
try {
for (int i = 0; i < 100; i++) {
pocket.getFreshReceiveAddress();
}
} catch (Bip44KeyLookAheadExceededException e) {
// try {
// pocket.getFreshReceiveAddress();
// } catch (Bip44KeyLookAheadExceededException e1) { /* ignore */ }
assertFalse(pocket.canCreateFreshReceiveAddress());
// We used 18, so the total must be (20-1)+18=37
assertEquals(37, pocket.getNumberIssuedReceiveAddresses());
assertEquals(37, pocket.getIssuedReceiveAddresses().size());
}
}
@Test
public void issuedKeysLimit2() throws Exception {
assertTrue(pocket.canCreateFreshReceiveAddress());
try {
for (int i = 0; i < 100; i++) {
pocket.getFreshReceiveAddress();
}
} catch (Bip44KeyLookAheadExceededException e) {
assertFalse(pocket.canCreateFreshReceiveAddress());
// We haven't used any key so the total must be 20 - 1 (the unused key)
assertEquals(19, pocket.getNumberIssuedReceiveAddresses());
assertEquals(19, pocket.getIssuedReceiveAddresses().size());
}
}
@Test
public void usedAddresses() throws Exception {
assertEquals(0, pocket.getUsedAddresses().size());
pocket.onConnection(getBlockchainConnection(DOGE));
// Receive and change addresses
assertEquals(13, pocket.getUsedAddresses().size());
}
private Sha256Hash send(Value value, WalletPocketHD w1, WalletPocketHD w2) throws Exception {
assertEquals(w1.getCoinType(), w2.getCoinType());
CoinType type = w1.getCoinType();
BitSendRequest req = w1.sendCoinsOffline(w2.getReceiveAddress(), value);
req.feePerTxSize = type.value("0.01");
w1.completeAndSignTx(req);
byte[] txBytes = req.tx.bitcoinSerialize();
w1.addNewTransactionIfNeeded(new BitTransaction(type, txBytes));
w2.addNewTransactionIfNeeded(new BitTransaction(type, txBytes));
return req.tx.getHash();
}
@Test
public void testSendingAndBalances() throws Exception {
DeterministicHierarchy h = new DeterministicHierarchy(masterKey);
WalletPocketHD account1 = new WalletPocketHD(h.get(BTC.getBip44Path(0), false, true), BTC, null, null);
WalletPocketHD account2 = new WalletPocketHD(h.get(BTC.getBip44Path(1), false, true), BTC, null, null);
WalletPocketHD account3 = new WalletPocketHD(h.get(BTC.getBip44Path(2), false, true), BTC, null, null);
Transaction tx = new Transaction(BTC);
tx.addOutput(BTC.oneCoin().toCoin(), account1.getReceiveAddress());
tx.getConfidence().setSource(Source.SELF);
account1.addNewTransactionIfNeeded(tx);
assertEquals(BTC.value("1"), account1.getBalance());
assertEquals(BTC.value("0"), account2.getBalance());
assertEquals(BTC.value("0"), account3.getBalance());
Sha256Hash txId = send(BTC.value("0.05"), account1, account2);
assertEquals(BTC.value("0.94"), account1.getBalance());
assertEquals(BTC.value("0"), account2.getBalance());
assertEquals(BTC.value("0"), account3.getBalance());
setTrustedTransaction(account1, txId);
setTrustedTransaction(account2, txId);
assertEquals(BTC.value("0.94"), account1.getBalance());
assertEquals(BTC.value("0.05"), account2.getBalance());
txId = send(BTC.value("0.07"), account1, account3);
setTrustedTransaction(account1, txId);
setTrustedTransaction(account3, txId);
assertEquals(BTC.value("0.86"), account1.getBalance());
assertEquals(BTC.value("0.05"), account2.getBalance());
assertEquals(BTC.value("0.07"), account3.getBalance());
txId = send(BTC.value("0.03"), account2, account3);
setTrustedTransaction(account2, txId);
setTrustedTransaction(account3, txId);
assertEquals(BTC.value("0.86"), account1.getBalance());
assertEquals(BTC.value("0.01"), account2.getBalance());
assertEquals(BTC.value("0.1"), account3.getBalance());
}
private void setTrustedTransaction(WalletPocketHD account, Sha256Hash txId) {
BitTransaction tx = checkNotNull(account.getTransaction(txId));
tx.setSource(Source.SELF);
}
@Test
public void testLoading() throws Exception {
assertFalse(pocket.isLoading());
pocket.onConnection(getBlockchainConnection(DOGE));
// TODO add fine grained control to the blockchain connection in order to test the loading status
assertFalse(pocket.isLoading());
}
@Test
public void fillTransactions() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
checkUnspentOutputs(getDummyUtxoSet(), pocket);
assertEquals(11000000000L, pocket.getBalance().value);
// Issued keys
assertEquals(18, pocket.keys.getNumIssuedExternalKeys());
assertEquals(9, pocket.keys.getNumIssuedInternalKeys());
// No addresses left to subscribe
List<AbstractAddress> addressesToWatch = pocket.getAddressesToWatch();
assertEquals(0, addressesToWatch.size());
// 18 external issued + 20 lookahead + 9 external issued + 20 lookahead
assertEquals(67, pocket.addressesStatus.size());
assertEquals(67, pocket.addressesSubscribed.size());
BitAddress receiveAddr = pocket.getReceiveAddress();
// This key is not issued
assertEquals(18, pocket.keys.getNumIssuedExternalKeys());
assertEquals(67, pocket.addressesStatus.size());
assertEquals(67, pocket.addressesSubscribed.size());
DeterministicKey key = pocket.keys.findKeyFromPubHash(receiveAddr.getHash160());
assertNotNull(key);
// 18 here is the key index, not issued keys count
assertEquals(18, key.getChildNumber().num());
assertEquals(11000000000L, pocket.getBalance().value);
}
@Test
public void serializeTransactionsBtc() throws Exception, Bip44KeyLookAheadExceededException {
WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null);
Transaction tx = new Transaction(BTC);
tx.addOutput(BTC.oneCoin().toCoin(), account.getReceiveAddress());
account.addNewTransactionIfNeeded(tx);
testWalletSerializationForCoin(account);
}
@Test
public void serializeTransactionsNbt() throws Exception, Bip44KeyLookAheadExceededException {
WalletPocketHD account = new WalletPocketHD(rootKey, NBT, null, null);
Transaction tx = new Transaction(NBT);
tx.addOutput(NBT.oneCoin().toCoin(), account.getReceiveAddress());
account.addNewTransactionIfNeeded(tx);
testWalletSerializationForCoin(account);
}
@Test
public void serializeTransactionsVpn() throws Exception, Bip44KeyLookAheadExceededException {
WalletPocketHD account = new WalletPocketHD(rootKey, VPN, null, null);
// Test tx with null extra bytes
Transaction tx = new Transaction(VPN);
tx.setTime(0x99999999);
tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress());
account.addNewTransactionIfNeeded(tx);
WalletPocketHD newAccount = testWalletSerializationForCoin(account);
Transaction newTx = newAccount.getRawTransaction(tx.getHash());
assertNotNull(newTx);
assertNotNull(newTx.getExtraBytes());
assertEquals(0, newTx.getExtraBytes().length);
// Test tx with empty extra bytes
tx = new Transaction(VPN);
tx.setTime(0x99999999);
tx.setExtraBytes(new byte[0]);
tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress());
account.addNewTransactionIfNeeded(tx);
newAccount = testWalletSerializationForCoin(account);
newTx = newAccount.getRawTransaction(tx.getHash());
assertNotNull(newTx);
assertNotNull(newTx.getExtraBytes());
assertEquals(0, newTx.getExtraBytes().length);
// Test tx with extra bytes
tx = new Transaction(VPN);
tx.setTime(0x99999999);
byte[] bytes = {0x1, 0x2, 0x3};
tx.setExtraBytes(bytes);
tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress());
account.addNewTransactionIfNeeded(tx);
newAccount = testWalletSerializationForCoin(account);
newTx = newAccount.getRawTransaction(tx.getHash());
assertNotNull(newTx);
assertArrayEquals(bytes, newTx.getExtraBytes());
}
private WalletPocketHD testWalletSerializationForCoin(WalletPocketHD account) throws UnreadableWalletException {
Protos.WalletPocket proto = account.toProtobuf();
WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null);
assertEquals(account.getBalance().value, newAccount.getBalance().value);
Map<Sha256Hash, BitTransaction> transactions = account.getTransactions();
Map<Sha256Hash, BitTransaction> newTransactions = newAccount.getTransactions();
for (Sha256Hash txId : transactions.keySet()) {
assertTrue(newTransactions.containsKey(txId));
assertEquals(transactions.get(txId), newTransactions.get(txId));
}
return newAccount;
}
@Test
public void serializeUnencryptedNormal() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
Protos.WalletPocket walletPocketProto = pocket.toProtobuf();
System.out.println(walletPocketProto.toString());
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null);
assertEquals(pocket.getBalance().value, newPocket.getBalance().value);
assertEquals(DOGE.value(11000000000l), newPocket.getBalance());
Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet();
checkUnspentOutputs(expectedUtxoSet, pocket);
checkUnspentOutputs(expectedUtxoSet, newPocket);
assertEquals(pocket.getCoinType(), newPocket.getCoinType());
assertEquals(pocket.getDescriptionOrCoinName(), newPocket.getDescriptionOrCoinName());
assertEquals(pocket.keys.toProtobuf().toString(), newPocket.keys.toProtobuf().toString());
assertEquals(pocket.getLastBlockSeenHash(), newPocket.getLastBlockSeenHash());
assertEquals(pocket.getLastBlockSeenHeight(), newPocket.getLastBlockSeenHeight());
assertEquals(pocket.getLastBlockSeenTimeSecs(), newPocket.getLastBlockSeenTimeSecs());
for (BitTransaction tx : pocket.getTransactions().values()) {
assertEquals(tx, newPocket.getTransaction(tx.getHash()));
BitTransaction txNew = checkNotNull(newPocket.getTransaction(tx.getHash()));
assertInputsEquals(tx.getInputs(), txNew.getInputs());
assertOutputsEquals(tx.getOutputs(false), txNew.getOutputs(false));
}
for (AddressStatus status : pocket.getAllAddressStatus()) {
if (status.getStatus() == null) continue;
assertEquals(status, newPocket.getAddressStatus(status.getAddress()));
}
// Issued keys
assertEquals(18, newPocket.keys.getNumIssuedExternalKeys());
assertEquals(9, newPocket.keys.getNumIssuedInternalKeys());
newPocket.onConnection(getBlockchainConnection(DOGE));
// No addresses left to subscribe
List<AbstractAddress> addressesToWatch = newPocket.getAddressesToWatch();
assertEquals(0, addressesToWatch.size());
// 18 external issued + 20 lookahead + 9 external issued + 20 lookahead
assertEquals(67, newPocket.addressesStatus.size());
assertEquals(67, newPocket.addressesSubscribed.size());
}
private void assertInputsEquals(List<TransactionInput> expected, List<TransactionInput> actual) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize());
}
}
private void assertOutputsEquals(List<TransactionOutput> expected, List<TransactionOutput> actual) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize());
}
}
@Test
public void serializeUnencryptedEmpty() throws Exception {
pocket.maybeInitializeAllKeys();
Protos.WalletPocket walletPocketProto = pocket.toProtobuf();
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null);
assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString());
// Issued keys
assertEquals(0, newPocket.keys.getNumIssuedExternalKeys());
assertEquals(0, newPocket.keys.getNumIssuedInternalKeys());
// 20 lookahead + 20 lookahead
assertEquals(40, newPocket.keys.getActiveKeys().size());
}
@Test
public void serializeEncryptedEmpty() throws Exception {
pocket.maybeInitializeAllKeys();
pocket.encrypt(crypter, aesKey);
Protos.WalletPocket walletPocketProto = pocket.toProtobuf();
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, crypter);
assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString());
pocket.decrypt(aesKey);
// One is encrypted, so they should not match
assertNotEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString());
newPocket.decrypt(aesKey);
assertEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString());
}
@Test
public void serializeEncryptedNormal() throws Exception {
pocket.maybeInitializeAllKeys();
pocket.encrypt(crypter, aesKey);
pocket.onConnection(getBlockchainConnection(DOGE));
assertEquals(DOGE.value(11000000000l), pocket.getBalance());
assertAllKeysEncrypted(pocket);
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(pocket.toProtobuf(), crypter);
assertEquals(DOGE.value(11000000000l), newPocket.getBalance());
Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet();
checkUnspentOutputs(expectedUtxoSet, pocket);
checkUnspentOutputs(expectedUtxoSet, newPocket);
assertAllKeysEncrypted(newPocket);
pocket.decrypt(aesKey);
newPocket.decrypt(aesKey);
assertAllKeysDecrypted(pocket);
assertAllKeysDecrypted(newPocket);
}
private void checkUnspentOutputs(Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet, WalletPocketHD pocket) {
Map<TrimmedOutPoint, OutPointOutput> pocketUtxoSet = pocket.getUnspentOutputs(false);
for (OutPointOutput utxo : expectedUtxoSet.values()) {
assertEquals(utxo, pocketUtxoSet.get(utxo.getOutPoint()));
}
}
private void assertAllKeysDecrypted(WalletPocketHD pocket) {
List<ECKey> keys = pocket.keys.getKeys(false);
for (ECKey k : keys) {
DeterministicKey key = (DeterministicKey) k;
assertFalse(key.isEncrypted());
}
}
private void assertAllKeysEncrypted(WalletPocketHD pocket) {
List<ECKey> keys = pocket.keys.getKeys(false);
for (ECKey k : keys) {
DeterministicKey key = (DeterministicKey) k;
assertTrue(key.isEncrypted());
}
}
@Test
public void createDustTransactionFee() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp");
Value softDust = DOGE.getSoftDustLimit();
assertNotNull(softDust);
// Send a soft dust
BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, softDust.subtract(DOGE.value(1)));
pocket.completeTransaction(sendRequest);
assertEquals(DOGE.getFeeValue().multiply(2), sendRequest.tx.getFee());
}
@Test
public void createTransactionAndBroadcast() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp");
Value orgBalance = pocket.getBalance();
BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, DOGE.value(AMOUNT_TO_SEND));
sendRequest.shuffleOutputs = false;
sendRequest.feePerTxSize = DOGE.value(0);
pocket.completeTransaction(sendRequest);
// FIXME, mock does not work here
// pocket.broadcastTx(tx);
pocket.addNewTransactionIfNeeded(sendRequest.tx);
assertEquals(orgBalance.subtract(AMOUNT_TO_SEND), pocket.getBalance());
}
// Util methods
////////////////////////////////////////////////////////////////////////////////////////////////
public class MessageComparator implements Comparator<ChildMessage> {
@Override
public int compare(ChildMessage o1, ChildMessage o2) {
String s1 = Utils.HEX.encode(o1.bitcoinSerialize());
String s2 = Utils.HEX.encode(o2.bitcoinSerialize());
return s1.compareTo(s2);
}
}
HashMap<AbstractAddress, AddressStatus> getDummyStatuses() throws AddressMalformedException {
HashMap<AbstractAddress, AddressStatus> status = new HashMap<>(40);
for (int i = 0; i < addresses.size(); i++) {
AbstractAddress address = DOGE.newAddress(addresses.get(i));
status.put(address, new AddressStatus(address, statuses[i]));
}
return status;
}
private HashMap<AbstractAddress, ArrayList<HistoryTx>> getDummyHistoryTXs() throws AddressMalformedException, JSONException {
HashMap<AbstractAddress, ArrayList<HistoryTx>> htxs = new HashMap<>(40);
for (int i = 0; i < statuses.length; i++) {
JSONArray jsonArray = new JSONArray(history[i]);
ArrayList<HistoryTx> list = new ArrayList<>();
for (int j = 0; j < jsonArray.length(); j++) {
list.add(new HistoryTx(jsonArray.getJSONObject(j)));
}
htxs.put(DOGE.newAddress(addresses.get(i)), list);
}
return htxs;
}
private HashMap<AbstractAddress, ArrayList<UnspentTx>> getDummyUnspentTXs() throws AddressMalformedException, JSONException {
HashMap<AbstractAddress, ArrayList<UnspentTx>> utxs = new HashMap<>(40);
for (int i = 0; i < statuses.length; i++) {
JSONArray jsonArray = new JSONArray(unspent[i]);
ArrayList<UnspentTx> list = new ArrayList<>();
for (int j = 0; j < jsonArray.length(); j++) {
list.add(new UnspentTx(jsonArray.getJSONObject(j)));
}
utxs.put(DOGE.newAddress(addresses.get(i)), list);
}
return utxs;
}
private Map<TrimmedOutPoint, OutPointOutput> getDummyUtxoSet() throws AddressMalformedException, JSONException {
final HashMap<TrimmedOutPoint, OutPointOutput> unspentOutputs = new HashMap<>();
for (int i = 0; i < statuses.length; i++) {
BitAddress address = (BitAddress) DOGE.newAddress(addresses.get(i));
JSONArray utxoArray = new JSONArray(unspent[i]);
for (int j = 0; j < utxoArray.length(); j++) {
JSONObject utxoObject = utxoArray.getJSONObject(j);
//"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]",
TrimmedOutPoint outPoint = new TrimmedOutPoint(DOGE, utxoObject.getInt("tx_pos"),
new Sha256Hash(utxoObject.getString("tx_hash")));
TransactionOutput output = new TransactionOutput(DOGE, null,
Coin.valueOf(utxoObject.getLong("value")), address);
OutPointOutput utxo = new OutPointOutput(outPoint, output, false);
unspentOutputs.put(outPoint, utxo);
}
}
return unspentOutputs;
}
private HashMap<Sha256Hash, byte[]> getDummyRawTXs() throws AddressMalformedException, JSONException {
HashMap<Sha256Hash, byte[]> rawTxs = new HashMap<>();
for (String[] tx : txs) {
rawTxs.put(new Sha256Hash(tx[0]), Utils.HEX.decode(tx[1]));
}
return rawTxs;
}
class MockBlockchainConnection implements BitBlockchainConnection {
final HashMap<AbstractAddress, AddressStatus> statuses;
final HashMap<AbstractAddress, ArrayList<HistoryTx>> historyTxs;
final HashMap<AbstractAddress, ArrayList<UnspentTx>> unspentTxs;
final HashMap<Sha256Hash, byte[]> rawTxs;
private CoinType coinType;
MockBlockchainConnection(CoinType coinType) throws Exception {
this.coinType = coinType;
statuses = getDummyStatuses();
historyTxs = getDummyHistoryTXs();
unspentTxs = getDummyUnspentTXs();
rawTxs = getDummyRawTXs();
}
@Override
public void getBlock(int height, TransactionEventListener<BitTransaction> listener) { }
@Override
public void subscribeToBlockchain(TransactionEventListener<BitTransaction> listener) {
listener.onNewBlock(new BlockHeader(coinType, blockTimestamp, blockHeight));
}
@Override
public void subscribeToAddresses(List<AbstractAddress> addresses, TransactionEventListener<BitTransaction> listener) {
for (AbstractAddress a : addresses) {
AddressStatus status = statuses.get(a);
if (status == null) {
status = new AddressStatus(a, null);
}
listener.onAddressStatusUpdate(status);
}
}
@Override
public void getHistoryTx(AddressStatus status, TransactionEventListener<BitTransaction> listener) {
List<HistoryTx> htx = historyTxs.get(status.getAddress());
if (htx == null) {
htx = ImmutableList.of();
}
listener.onTransactionHistory(status, htx);
}
@Override
public void getUnspentTx(AddressStatus status, BitTransactionEventListener listener) {
List<UnspentTx> utx = unspentTxs.get(status.getAddress());
if (utx == null) {
utx = ImmutableList.of();
}
listener.onUnspentTransactionUpdate(status, utx);
}
@Override
public void getTransaction(Sha256Hash txHash, TransactionEventListener<BitTransaction> listener) {
BitTransaction tx = new BitTransaction(coinType, rawTxs.get(txHash));
listener.onTransactionUpdate(tx);
}
@Override
public void broadcastTx(BitTransaction tx, TransactionEventListener<BitTransaction> listener) {
// List<AddressStatus> newStatuses = new ArrayList<AddressStatus>();
// Random rand = new Random();
// byte[] randBytes = new byte[32];
// // Get spent outputs and modify statuses
// for (TransactionInput txi : tx.getInputs()) {
// UnspentTx unspentTx = new UnspentTx(
// txi.getOutpoint(), txi.getValue().value, 0);
//
// for (Map.Entry<Address, ArrayList<UnspentTx>> entry : utxs.entrySet()) {
// if (entry.getValue().remove(unspentTx)) {
// rand.nextBytes(randBytes);
// AddressStatus newStatus = new AddressStatus(entry.getKey(), Utils.HEX.encode(randBytes));
// statuses.put(entry.getKey(), newStatus);
// newStatuses.add(newStatus);
// }
// }
// }
//
// for (TransactionOutput txo : tx.getOutputs()) {
// if (txo.getAddressFromP2PKHScript(coinType) != null) {
// Address address = txo.getAddressFromP2PKHScript(coinType);
// if (addresses.contains(address.toString())) {
// AddressStatus newStatus = new AddressStatus(address, tx.getHashAsString());
// statuses.put(address, newStatus);
// newStatuses.add(newStatus);
// if (!utxs.containsKey(address)) {
// utxs.put(address, new ArrayList<UnspentTx>());
// }
// ArrayList<UnspentTx> unspentTxs = utxs.get(address);
// unspentTxs.add(new UnspentTx(txo.getOutPointFor(),
// txo.getValue().value, 0));
// if (!historyTxs.containsKey(address)) {
// historyTxs.put(address, new ArrayList<HistoryTx>());
// }
// ArrayList<HistoryTx> historyTxes = historyTxs.get(address);
// historyTxes.add(new HistoryTx(txo.getOutPointFor(), 0));
// }
// }
// }
//
// rawTxs.put(tx.getHash(), tx.bitcoinSerialize());
//
// for (AddressStatus newStatus : newStatuses) {
// listener.onAddressStatusUpdate(newStatus);
// }
}
@Override
public boolean broadcastTxSync(BitTransaction tx) {
return false;
}
@Override
public void ping(String versionString) {}
@Override
public void addEventListener(ConnectionEventListener listener) {
}
@Override
public void resetConnection() {
}
@Override
public void stopAsync() {
}
@Override
public boolean isActivelyConnected() {
return false;
}
@Override
public void startAsync() {
}
}
private MockBlockchainConnection getBlockchainConnection(CoinType coinType) throws Exception {
return new MockBlockchainConnection(coinType);
}
// Mock data
long blockTimestamp = 1411000000l;
int blockHeight = 200000;
List<String> addresses = ImmutableList.of(
"nnfP8VuPfZXhNtMDzvX1bKurzcV1k7HNrQ",
"nf4AUKiaGdx4GTbbh222KvtuCbAuvbcdE2",
"npGkmbWtdWybFNSZQXUK6zZxbEocMtrTzz",
"nVaN45bbs6AUc1EUpP71hHGBGb2qciNrJc",
"nrdHFZP1AfdKBrjsSQmwFm8R2i2mzMef75",
"niGZgfbhFYn6tJqksmC8CnzSRL1GHNsu7e",
"nh6w8yu1zoKYoT837ffkVmuPjTaP69Pc5E",
"nbyMgmEghsL9tpk7XfdH9gLGudh6Lrbbuf",
"naX9akzYuWY1gKbcZo3t36aBKc1gqbzgSs",
"nqcPVTGeAfCowELB2D5PdVF3FWFjFtkkFf",
"nd4vVvPTpp2LfcsMPsmG3Dh7MFAsqRHp4g",
"nVK4Uz5Sf56ygrr6RiwXcRvH8AuUVbjjHi",
"nbipkRwT1NCSXZSrm8uAAEgQAA2s2NWMkG",
"nZU6QAMAdCQcVDxEmL7GEY6ykFm8m6u6am",
"nbFqayssM5s7hLjLFwf2d95JXKRWBk2pBH",
"nacZfcNgVi47hamLscWdUGQhUQGGpSdgq8",
"niiMT7ZYeFnaLPYtqQFBBX1sP3dT5JtcEw",
"ns6GyTaniLWaiYrvAf5tk4D8tWrbcCLGyj",
"nhdwQfptLTzLJGbLF3vvtqyBaqPMPecDmE",
"neMUAGeTzwxLbSkXMsdmWf1fTKS1UsJjXY",
"nXsAMeXxtpx8jaxnU3Xv9ZQ6ZcRcD1xYhR",
"ns35rKnnWf6xP3KSj5WPkMCVVaADGi6Ndk",
"nk4wcXYBEWs5HkhNLsuaQJoAjJHoK6SQmG",
"npsJQWu8fsALoTPum8D4j8FDkyeusk8fU8",
"nZNhZo4Vz3DnwQGPL3SJTZgUw2Kh4g9oay",
"nnxDTYB8WMHMgLnCY2tuaEtysvdhRnWehZ",
"nb2iaDXG1EqkcE47H87WQFkQNkeVK66Z21",
"nWHAkpn2DB3DJRsbiK3vpbigoa3M2uVuF8",
"nViKdC7Gm6TMmCuWTBwVE9i4rJhyfwbfqg",
"nZQV5BifbGPzaxTrB4efgHruWH5rufemqP",
"nVvZaLvnkCVAzpLYPoHeqU4w9zJ5yrZgUn",
"nrMp6pRCk98WYWkCWq9Pqthz9HbpQu8BT3",
"nnA3aYsLqysKT6gAu1dr4EKm586cmKiRxS",
"nVfcVgMY7DL6nqoSxwJy7B7hKXirQwj6ic",
"ni4oAzi6nCVuEdjoHyVMVKWb1DqTd3qY3H",
"nnpf3gx442yomniRJPMGPapgjHrraPZXxJ",
"nkuFnF8wUmHFkMycaFMvyjBoiMeR5KBKGd",
"nXKccwjaUyrQkLrdqKT6aq6cDiFgBBVgNz",
"nZMSNsXSAL7i1YD6KP5FrhATuZ2CWvnxqR",
"nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q"
);
String[] statuses = {
"fe7c109d8bd90551a406cf0b3499117db04bc9c4f48e1df27ac1cf3ddcb3d464",
"8a53babd831c6c3a857e20190e884efe75a005bdd7cd273c4f27ab1b8ec81c2d",
"86bc2f0cf0112fd59c9aadfe5c887062c21d7a873db260dff68dcfe4417fe212",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
};
String[] unspent = {
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 1, \"value\": 1000000000, \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 2, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"tx_pos\": 0, \"value\": 1000000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 3, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 4, \"value\": 1000000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 12, \"value\": 1000000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 13, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 6, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 7, \"value\": 1000000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 8, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 9, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 10, \"value\": 1000000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]"
};
String[] history = {
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]"
};
String[][] txs = {
{"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f", "0100000001b8778dff640ccb144346d9db48201639b2707a0cc59e19672d2dd76cc6d1a5a6010000006b48304502210098d2e5b8a6c72442430bc09f2f4bcb56612c5b9e5eee821d65b412d099bb723402204f7f008ac052e5d7be0ab5b0c85ea5e627d725a521bd9e9b193d1fdf81c317a0012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0e0065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00ca9a3b000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac0065cd1d000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac0065cd1d000000001976a9140f2b1e5b376e22c5d1e635233eb90cf50ad9095188ac00ca9a3b000000001976a914f612ffd50b6a69df5e34ee0c5b529dfaaedca03d88ac00f633bce60000001976a914937258e3a8c463ec07e78ce62326c488170ad25e88ac0065cd1d000000001976a9142848ad5ff4cc32df3649646017c47bc04e8d211788ac00ca9a3b000000001976a914fa937737a6df2b8a5e39cce8b0bdd9510683023a88ac0065cd1d000000001976a914ae248a5d710143b6b309aaab9ce17059536e2aa388ac0065cd1d000000001976a91438d6eb11eca405be497a7183c50e437851425e0088ac00ca9a3b000000001976a91410ac6b2704146b50a1dd8f6df70736856ebf8b3488ac0065cd1d000000001976a914456816dccb3a4f33ae2dbd3ba623997075d5c73d88ac00ca9a3b000000001976a91452957c44e5bee9a60402a739fc8959c2850ea98488ac0065cd1d000000001976a914fb2dffa402d05f74335d137e21e41d8920c745fb88ac00000000"},
{"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae", "01000000011a656d67706db286d1e6fad57eb4f411cb14f8880cea8348da339b9d434a5ec7050000006a47304402201d69fddb269b53aa742ff6437a45adb4ca5c59f666c9b4eabc4a0c7a6e6f4c0f022015a747b7a6d9371a4020f5b396dcd094b0f36af3fc82e95091da856181912dfa012102c9a8d5b2f768afe30ee772d185e7a61f751be05649a79508b38a2be8824adec3ffffffff020065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00b07098e60000001976a9141630d812e219e6bcbe494eb96f7a7900c216ad5d88ac00000000"},
{"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb", "010000000164a3990893c012b20287d43d1071ac26f4b93648ff4213db6da6979beed6b7dc010000006b48304502210086ac11d4a8146b4176a72059960690c72a9776468cd671fd07c064b51f24961d02205bcf008d6995014f3cfd79100ee9beab5688c88cca15c5cea38b769563785d900121036530415a7b3b9c5976f26a63a57d119ab39491762121723c773399a2531a1bd7ffffffff020065cd1d000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac006aad74e60000001976a914e5616848352c328c9f61b167eb1b0fde39b5cb6788ac00000000"},
{"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7", "010000000141c217dfea3a1d8d6a06e9d3daf75b292581f652256d73a7891e5dc9c7ee3cca000000006a47304402205cce451228f98fece9645052546b82c2b2d425a4889b03999001fababfc7f4690220583b2189faef07d6b0191c788301cfab1b3f47ffe2c403d632b92c6dde27e14f012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0100ca9a3b000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac00000000"}
};
} | AraguaneyBits/araguaneybits-wallet | core/src/test/java/com/araguaneybits/core/wallet/WalletPocketHDTest.java |
45,869 | /**
* Copyright (C) 2013-2017 Vasilis Vryniotis <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datumbox.framework.core.common.text;
import com.datumbox.framework.tests.abstracts.AbstractTest;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Test cases for StringCleaner.
*
* @author Vasilis Vryniotis <[email protected]>
*/
public class StringCleanerTest extends AbstractTest {
/**
* Test of tokenizeURLs method, of class StringCleaner.
*/
@Test
public void testTokenizeURLs() {
logger.info("tokenizeURLs");
String text = "Test, test δοκιμή http://wWw.Google.com/page?query=1#hash test test";
String expResult = "Test, test δοκιμή PREPROCESSDOC_URL test test";
String result = StringCleaner.tokenizeURLs(text);
assertEquals(expResult, result);
}
/**
* Test of tokenizeSmileys method, of class StringCleaner.
*/
@Test
public void testTokenizeSmileys() {
logger.info("tokenizeSmileys");
String text = "Test, test δοκιμή :) :( :] :[ test test";
String expResult = "Test, test δοκιμή PREPROCESSDOC_EM1 PREPROCESSDOC_EM3 PREPROCESSDOC_EM8 PREPROCESSDOC_EM9 test test";
String result = StringCleaner.tokenizeSmileys(text);
assertEquals(expResult, result);
}
/**
* Test of removeExtraSpaces method, of class StringCleaner.
*/
@Test
public void testRemoveExtraSpaces() {
logger.info("removeExtraSpaces");
String text = " test test test test test\n\n\n\r\n\r\r test\n";
String expResult = "test test test test test test";
String result = StringCleaner.removeExtraSpaces(text);
assertEquals(expResult, result);
}
/**
* Test of removeSymbols method, of class StringCleaner.
*/
@Test
public void testRemoveSymbols() {
logger.info("removeSymbols");
String text = "test ` ~ ! @ # $ % ^ & * ( ) _ - + = < , > . ? / \" ' : ; [ { } ] | \\ test `~!@#$%^&*()_-+=<,>.?/\\\"':;[{}]|\\\\ test";
String expResult = "test _ test _ test";
String result = StringCleaner.removeExtraSpaces(StringCleaner.removeSymbols(text));
assertEquals(expResult, result);
}
/**
* Test of unifyTerminators method, of class StringCleaner.
*/
@Test
public void testUnifyTerminators() {
logger.info("unifyTerminators");
String text = " This is amazing!!! ! How is this possible?!?!?!?!!!???! ";
String expResult = "This is amazing. How is this possible.";
String result = StringCleaner.unifyTerminators(text);
assertEquals(expResult, result);
}
/**
* Test of removeAccents method, of class StringCleaner.
*/
@Test
public void testRemoveAccents() {
logger.info("removeAccents");
String text = "'ά','ό','έ','ί','ϊ','ΐ','ή','ύ','ϋ','ΰ','ώ','à','á','â','ã','ä','ç','è','é','ê','ë','ì','í','î','ï','ñ','ò','ó','ô','õ','ö','ù','ú','û','ü','ý','ÿ','Ά','Ό','Έ','Ί','Ϊ','Ή','Ύ','Ϋ','Ώ','À','Á','Â','Ã','Ä','Ç','È','É','Ê','Ë','Ì','Í','Î','Ï','Ñ','Ò','Ó','Ô','Õ','Ö','Ù','Ú','Û','Ü','Ý'";
String expResult = "'α','ο','ε','ι','ι','ι','η','υ','υ','υ','ω','a','a','a','a','a','c','e','e','e','e','i','i','i','i','n','o','o','o','o','o','u','u','u','u','y','y','Α','Ο','Ε','Ι','Ι','Η','Υ','Υ','Ω','A','A','A','A','A','C','E','E','E','E','I','I','I','I','N','O','O','O','O','O','U','U','U','U','Y'";
String result = StringCleaner.removeAccents(text);
assertEquals(expResult, result);
}
}
| tukejai/datumbox-framework | datumbox-framework-core/src/test/java/com/datumbox/framework/core/common/text/StringCleanerTest.java |
45,870 | package android.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* loaded from: gencallgraphv3.jar:android-4.1.1.4.jar:android/util/Patterns.class */
public class Patterns {
public static final String TOP_LEVEL_DOMAIN_STR = "((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw])";
public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL = "(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))";
public static final String GOOD_IRI_CHAR = "a-zA-Z0-9 -\ud7ff豈-﷏ﷰ-\uffef";
public static final Pattern TOP_LEVEL_DOMAIN = null;
public static final Pattern WEB_URL = null;
public static final Pattern IP_ADDRESS = null;
public static final Pattern DOMAIN_NAME = null;
public static final Pattern EMAIL_ADDRESS = null;
public static final Pattern PHONE = null;
Patterns() {
throw new RuntimeException("Stub!");
}
public static final String concatGroups(Matcher matcher) {
throw new RuntimeException("Stub!");
}
public static final String digitsAndPlusOnly(Matcher matcher) {
throw new RuntimeException("Stub!");
}
}
| jdanceze/cg_parser | cg_src/sources/android/util/Patterns.java |
45,871 | package com.hankcs.hanlp.tokenizer.pipe;
import com.hankcs.hanlp.model.crf.CRFLexicalAnalyzer;
import com.hankcs.hanlp.seg.SegmentPipeline;
import junit.framework.TestCase;
import java.util.regex.Pattern;
public class SegmentPipelineTest extends TestCase
{
private static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(((([a-zA-Z0-9][a-zA-Z0-9\\-]*)*[a-zA-Z0-9]\\.)+((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?");
private static final Pattern EMAIL = Pattern.compile("(\\w+(?:[-+.]\\w+)*)@(\\w+(?:[-.]\\w+)*\\.\\w+(?:[-.]\\w+)*)");
public void testSegment() throws Exception
{
SegmentPipeline pipeline = new SegmentPipeline(new CRFLexicalAnalyzer());
pipeline.add(new RegexRecognizePipe(EMAIL, "【邮件】"));
pipeline.add(new RegexRecognizePipe(WEB_URL, "【网址】"));
String text = "HanLP的项目地址是https://github.com/hankcs/HanLP," +
"联系邮箱[email protected]";
System.out.println(pipeline.seg(text));
}
} | bage2014/study | study-hanlp/src/test/java/com/hankcs/hanlp/tokenizer/pipe/SegmentPipelineTest.java |
45,873 | /*
* <author>Han He</author>
* <email>[email protected]</email>
* <create-date>2018-11-10 10:51 AM</create-date>
*
* <copyright file="DemoPipeline.java">
* Copyright (c) 2018, Han He. All Rights Reserved, http://www.hankcs.com/
* See LICENSE file in the project root for full license information.
* </copyright>
*/
package demo.hankcs.demo;
import demo.hankcs.hanlp.corpus.document.sentence.word.IWord;
import demo.hankcs.hanlp.model.perceptron.PerceptronLexicalAnalyzer;
import demo.hankcs.hanlp.tokenizer.pipe.LexicalAnalyzerPipeline;
import demo.hankcs.hanlp.tokenizer.pipe.Pipe;
import demo.hankcs.hanlp.tokenizer.pipe.RegexRecognizePipe;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
/**
* 演示流水线模式,几个概念:
* - pipe:流水线的一节管道,执行统计分词或规则逻辑
* - flow:管道的数据流,在同名方法中执行本节管道的业务
* - pipeline:流水线,由至少一节管道(统计分词管道)构成,可自由调整管道的拼装方式
*
* @author hankcs
*/
public class DemoPipeline
{
private static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(((([a-zA-Z0-9][a-zA-Z0-9\\-]*)*[a-zA-Z0-9]\\.)+((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?");
private static final Pattern EMAIL = Pattern.compile("(\\w+(?:[-+.]\\w+)*)@(\\w+(?:[-.]\\w+)*\\.\\w+(?:[-.]\\w+)*)");
public static void main(String[] args) throws IOException
{
LexicalAnalyzerPipeline analyzer = new LexicalAnalyzerPipeline(new PerceptronLexicalAnalyzer());
// 管道顺序=优先级,自行调整管道顺序以控制优先级
analyzer.addFirst(new RegexRecognizePipe(WEB_URL, "【网址】"));
analyzer.addFirst(new RegexRecognizePipe(EMAIL, "【邮件】"));
analyzer.addLast(new Pipe<List<IWord>, List<IWord>>() // 自己写个管道也并非难事
{
@Override
public List<IWord> flow(List<IWord> input)
{
for (IWord word : input)
{
if ("nx".equals(word.getLabel()))
word.setLabel("字母");
}
return input;
}
});
String text = "HanLP的项目地址是https://github.com/hankcs/HanLP,联系邮箱[email protected]";
System.out.println(analyzer.analyze(text));
}
}
| Harries/springboot-demo | hanlp/src/test/java/demo/hankcs/demo/DemoPipeline.java |
45,876 | package demo.hankcs.hanlp.tokenizer.pipe;
import demo.hankcs.hanlp.model.crf.CRFLexicalAnalyzer;
import demo.hankcs.hanlp.seg.SegmentPipeline;
import junit.framework.TestCase;
import java.util.regex.Pattern;
public class SegmentPipelineTest extends TestCase
{
private static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(((([a-zA-Z0-9][a-zA-Z0-9\\-]*)*[a-zA-Z0-9]\\.)+((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?");
private static final Pattern EMAIL = Pattern.compile("(\\w+(?:[-+.]\\w+)*)@(\\w+(?:[-.]\\w+)*\\.\\w+(?:[-.]\\w+)*)");
public void testSegment() throws Exception
{
SegmentPipeline pipeline = new SegmentPipeline(new CRFLexicalAnalyzer());
pipeline.add(new RegexRecognizePipe(EMAIL, "【邮件】"));
pipeline.add(new RegexRecognizePipe(WEB_URL, "【网址】"));
String text = "HanLP的项目地址是https://github.com/hankcs/HanLP," +
"联系邮箱[email protected]";
System.out.println(pipeline.seg(text));
}
} | Harries/springboot-demo | hanlp/src/test/java/demo/hankcs/hanlp/tokenizer/pipe/SegmentPipelineTest.java |
45,877 | package Tests;
import Jeu.Interfaces.Inventaire;
import Jeu.Modeles.InventaireSimple;
import org.junit.*;
import static org.junit.Assert.*;
/** Test le fonctionnement de l'inventaire.
* @author Basile Gros
* @version 2eme iteration
*/
public class InventaireTest{
// précision pour les comparaisons réelle
public final static double EPSILON = 10e-3;
Inventaire inventaire; /*L'inventaire testé*/
String objet1 = "Baton"; /*Des objets à ajouter à l'inventaire*/
String objet2 = "Caillou";
@Before public void setUp() {
inventaire = new InventaireSimple();
}
@Test public void testerAjoutSimple() {
inventaire.ajouter(objet1);
assertEquals("1x Baton.", inventaire.toString());
inventaire.ajouter(objet2);
assertEquals("1x Caillou,1x Baton.",inventaire.toString());
}
@Test public void testerAjoutMultiple() {
for (int i = 1; i <= 10; i++) {
inventaire.ajouter(objet1);
assertEquals(i+"x Baton.",inventaire.toString());
}
for (int i = 1; i <= 25; i++) {
inventaire.ajouter(objet2);
assertEquals(i+"x Caillou,10x Baton.",inventaire.toString());
}
}
@Test public void testerAjoutDesordre() {
inventaire.ajouter(objet1);
assertEquals("1x Baton.",inventaire.toString());
inventaire.ajouter(objet2);
assertEquals("1x Caillou,1x Baton.",inventaire.toString());
inventaire.ajouter(objet1);
assertEquals("1x Caillou,2x Baton.",inventaire.toString());
inventaire.ajouter(objet2);
assertEquals("2x Caillou,2x Baton.",inventaire.toString());
}
@Test public void testerAjouterVide() {
String objetVide = "";
inventaire.ajouter(objetVide);
assertEquals("", inventaire.toString());
inventaire.ajouter(objetVide);
assertEquals("",inventaire.toString());
inventaire.ajouter(objetVide);
assertEquals("",inventaire.toString());
}
@Test public void testerAjouterNull() {
String objetNull = null;
inventaire.ajouter(objetNull);
assertEquals("",inventaire.toString());
}
@Test public void testerAjoutCaracteresSpeciaux() {
String objetSpecial1 = "ç耧$ê£ì";
String objetSpecial2 = "Δοκιμή Контрольная работа";
inventaire.ajouter(objetSpecial1);
assertEquals("1x ç耧$ê£ì.",inventaire.toString());
inventaire.ajouter(objetSpecial2);
assertEquals("1x ç耧$ê£ì,1x Δοκιμή Контрольная работа.",inventaire.toString());
}
@Test public void testerSuppressionSimple() {
inventaire.ajouter(objet1);
assertEquals("1x Baton.",inventaire.toString());
inventaire.supprimer(objet1);
assertEquals("",inventaire.toString());
inventaire.ajouter(objet2);
assertEquals("1x Caillou.",inventaire.toString());
inventaire.supprimer(objet2);
assertEquals("",inventaire.toString());
}
@Test public void testerSuppressionMultiple() {
for (int i = 1; i <= 10; i++) {
inventaire.ajouter(objet1);
}
for (int i = 1; i <= 25; i++) {
inventaire.ajouter(objet2);
}
for (int i = 24; i >= 1; i--) {
inventaire.supprimer(objet2);
assertEquals(i+"x Caillou,10x Baton.",inventaire.toString());
}
inventaire.supprimer(objet2);
assertEquals("10x Baton.",inventaire.toString());
for (int i = 9; i >= 1; i--) {
inventaire.supprimer(objet1);
assertEquals(i+"x Baton.",inventaire.toString());
}
inventaire.supprimer(objet1);
assertEquals("",inventaire.toString());
}
@Test public void testSupprimerAbsent() {
inventaire.supprimer(objet1);
assertEquals("",inventaire.toString());
inventaire.supprimer(objet2);
assertEquals("",inventaire.toString());
}
@Test public void testSupprimerNull() {
String objetNull = null;
inventaire.ajouter(objetNull);
}
@Test public void testReinitialiser() {
for (int i = 1; i <= 10; i++) {
inventaire.ajouter(objet1);
}
assertEquals("10x Baton.",inventaire.toString());
inventaire.clear();
assertEquals("",inventaire.toString());
}
@Test public void testReinitialiserMultiplesObjets() {
for (int i = 1; i <= 10; i++) {
inventaire.ajouter(objet1);
inventaire.ajouter(objet2);
}
assertEquals("10x Caillou,10x Baton.",inventaire.toString());
inventaire.clear();
assertEquals("",inventaire.toString());
}
@Test public void testReinitialiserVide() {
assertEquals("",inventaire.toString());
inventaire.clear();
assertEquals("",inventaire.toString());
}
} | Hathoute/ENSEEIHT | TOB/tps/projet-long/GH-1/src/Tests/InventaireTest.java |
45,878 | package test;
import patternTree.PatternTreeMaker;
import trainingSet.UrlDecomposer;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
//import java.util.HashMap;
//import java.util.Map;
import java.util.*;
/**
* Created by navid
*/
public class test {
@Test
public void basicUrlDecomposerTest() throws MalformedURLException, UnsupportedEncodingException {
UrlDecomposer kvpc = new UrlDecomposer();
String urlStr = "HTTP://wWw.Example.cOm/";
HashMap<String, String> urlMap = new HashMap<>();
urlMap.put("protocol", "http");
urlMap.put("auth0", "com");
urlMap.put("auth1", "example");
urlMap.put("auth2", "www");
urlMap.put("port", "80");
Assert.assertEquals(kvpc.decompose(urlStr), urlMap);
}
@Test
public void fullFeatureUrlDecomposerTest() throws MalformedURLException, UnsupportedEncodingException {
UrlDecomposer decomposer = new UrlDecomposer();
String url1 = "http://wWw.Schönesdresden.DE:9090/%7EuserName/a%c2%b1b/Ex/search-results.jsp?Ne=292&N=461+21";
HashMap<String, String> urlMap1 = new HashMap<>();
urlMap1.put("protocol", "http");
urlMap1.put("port", "9090");
urlMap1.put("auth0", "de");
urlMap1.put("auth1", "schönesdresden");
urlMap1.put("auth2", "www");
urlMap1.put("path0", "~userName");
urlMap1.put("path1", "a±b");
urlMap1.put("path2", "Ex");
urlMap1.put("path3", "search-results.jsp");
urlMap1.put("&N", "461 21");
urlMap1.put("&Ne", "292");
Assert.assertEquals(decomposer.decompose(url1), urlMap1);
String defaultPort = "https://example.com/";
Assert.assertEquals((decomposer.decompose(defaultPort)).get("port"),"443");
String ceShiUrl = "http://例子.测试";
Assert.assertEquals((decomposer.decompose(ceShiUrl)).get("auth0"),"测试");
String dokimeUrl = "http://παράδειγμα.δοκιμή";
Assert.assertEquals((decomposer.decompose(dokimeUrl)).get("auth0"),"δοκιμή");
String url3 = "http://example.com/?1=a&&2=b&&&3=c&=d&&=e&&=f";
Assert.assertEquals(decomposer.decompose(url3).get("&1"), "a");
Assert.assertEquals(decomposer.decompose(url3).get("&&2"), "b");
Assert.assertEquals(decomposer.decompose(url3).get("&&&3"), "c");
Assert.assertEquals((decomposer.decompose(url3)).get("&"),"d");
Assert.assertEquals((decomposer.decompose(url3)).get("&&"),"f");
String url4 = "http://example.com/?1=a;2=b";
Assert.assertEquals((decomposer.decompose(url4)).get("&1"),"a;2=b");
String url5 = "http://example.com/?1=a&1=b";
Assert.assertEquals((decomposer.decompose(url5)).get("&1"),"b");
String url6 = "http://example.com/?=";
Assert.assertNull((decomposer.decompose(url6)).get("&"));
String nullUrl = null;
//TODO
String malformedUrl = "this is a malformed URL!";
//TODO
// Assert.assertThrows(decomposer.decompose(malformedUrl));
}
@Test
public void testSortByValue()
{
Random random = new Random(System.currentTimeMillis());
Map<String, Double> testMap = new HashMap<>(1000);
for(int i = 0 ; i < 1000 ; ++i) {
testMap.put( "SomeString" + random.nextInt(), random.nextInt()+.01);
}
testMap = PatternTreeMaker.sortMapByValue(testMap );
Assert.assertEquals( 1000, testMap.size() );
Double previous = null;
for(Map.Entry<String, Double> entry : testMap.entrySet()) {
Assert.assertNotNull( entry.getValue() );
if (previous != null) {
Assert.assertTrue( entry.getValue() >= previous );
}
previous = entry.getValue();
}
}
}
| navidyamani/learning-Url-Normalization-rules | src/test/java/test/test.java |
45,879 | package android.util;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Patterns {
public static final Pattern AUTOLINK_EMAIL_ADDRESS = Pattern.compile("((?:\\b|$|^)(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'\\.]{0,62}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'])?@(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63}))(?:\\b|$|^))");
public static final Pattern AUTOLINK_WEB_URL = Pattern.compile("(((?:\\b|$|^)(?:(?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))|((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^)))");
public static final Pattern AUTOLINK_WEB_URL_EMUI = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:" + DOMAIN_NAME_EMUI + ")(?:\\:\\d{1,5})?)((?:\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))+[\\;\\.\\=\\?\\/\\+\\)][a-zA-Z0-9\\%\\#\\&\\-\\_\\.\\~]*)|(?:\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*))?(?:\\b|$|(?=[ -豈-﷏ﷰ-]))", 2);
public static final Pattern DOMAIN_NAME = Pattern.compile(DOMAIN_NAME_STR);
public static final Pattern DOMAIN_NAME_EMUI = Pattern.compile("(([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}\\.)+[a-zA-Z]{2,63}|" + IP_ADDRESS + ")");
private static final String DOMAIN_NAME_STR = "(([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
public static final Pattern EMAIL_ADDRESS = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+");
private static final String EMAIL_ADDRESS_DOMAIN = "(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String EMAIL_ADDRESS_LOCAL_PART = "[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'\\.]{0,62}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'])?";
private static final String EMAIL_CHAR = "a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'";
private static final String GOOD_GTLD_CHAR_EMUI = "a-zA-Z";
@Deprecated
public static final String GOOD_IRI_CHAR = "a-zA-Z0-9 -豈-﷏ﷰ-";
public static final String GOOD_IRI_CHAR_EMUI = "a-zA-Z0-9";
private static final String GTLD_EMUI = "[a-zA-Z]{2,63}";
private static final String HOST_NAME = "([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String HOST_NAME_EMUI = "([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}\\.)+[a-zA-Z]{2,63}";
static final String IANA_TOP_LEVEL_DOMAINS = "(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))";
public static final Pattern IP_ADDRESS = Pattern.compile(IP_ADDRESS_STRING);
private static final String IP_ADDRESS_STRING = "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))";
private static final String IRI_EMUI = "[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}";
private static final String IRI_LABEL = "[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}";
private static final String LABEL_CHAR = "a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
private static final String PATH_AND_QUERY = "[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*";
public static final Pattern PHONE = Pattern.compile("(\\+[0-9]+[\\- \\.]*)?(\\([0-9]+\\)[\\- \\.]*)?([0-9][0-9\\- \\.]+[0-9])");
private static final String PORT_NUMBER = "\\:\\d{1,5}";
private static final String PROTOCOL = "(?i:http|https|rtsp)://";
private static final String PUNYCODE_TLD = "xn\\-\\-[\\w\\-]{0,58}\\w";
private static final String RELAXED_DOMAIN_NAME = "(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
private static final String STRICT_DOMAIN_NAME = "(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
private static final String STRICT_HOST_NAME = "(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))";
private static final String STRICT_TLD = "(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w)";
private static final String TLD = "(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String TLD_CHAR = "a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
@Deprecated
public static final Pattern TOP_LEVEL_DOMAIN = Pattern.compile(TOP_LEVEL_DOMAIN_STR);
@Deprecated
public static final String TOP_LEVEL_DOMAIN_STR = "((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw])";
@Deprecated
public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL = "(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))";
private static final String UCS_CHAR = "[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
private static final String USER_INFO = "(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@";
public static final Pattern WEB_URL = Pattern.compile("(((?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)([/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))");
private static final String WEB_URL_WITHOUT_PROTOCOL = "((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))";
private static final String WEB_URL_WITH_PROTOCOL = "((?:\\b|$|^)(?:(?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))";
private static final String WORD_BOUNDARY = "(?:\\b|$|^)";
public static final String concatGroups(Matcher matcher) {
StringBuilder b = new StringBuilder();
int numGroups = matcher.groupCount();
for (int i = 1; i <= numGroups; i++) {
String s = matcher.group(i);
if (s != null) {
b.append(s);
}
}
return b.toString();
}
public static final String digitsAndPlusOnly(Matcher matcher) {
StringBuilder buffer = new StringBuilder();
String matchingRegion = matcher.group();
int size = matchingRegion.length();
for (int i = 0; i < size; i++) {
char character = matchingRegion.charAt(i);
if (character == '+' || Character.isDigit(character)) {
buffer.append(character);
}
}
return buffer.toString();
}
private Patterns() {
}
public static Pattern getWebUrl() {
if (Locale.CHINESE.getLanguage().equals(Locale.getDefault().getLanguage())) {
return AUTOLINK_WEB_URL_EMUI;
}
return AUTOLINK_WEB_URL;
}
}
| dstmath/HWFramework | Mate20-9.0/src/main/java/android/util/Patterns.java |
45,880 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.codec.socks;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class SocksCmdRequestTest {
@Test
public void testConstructorParamsAreNotNull(){
try {
new SocksCmdRequest(null, SocksMessage.AddressType.UNKNOWN, "", 0);
} catch (Exception e){
assertTrue(e instanceof NullPointerException);
}
try {
new SocksCmdRequest(SocksMessage.CmdType.UNKNOWN, null, "", 0);
} catch (Exception e){
assertTrue(e instanceof NullPointerException);
}
try {
new SocksCmdRequest(SocksMessage.CmdType.UNKNOWN, SocksMessage.AddressType.UNKNOWN, null, 0);
} catch (Exception e){
assertTrue(e instanceof NullPointerException);
}
}
@Test
public void testIPv4CorrectAddress(){
try {
new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.IPv4, "54.54.1111.253", 0);
} catch (Exception e){
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testIPv6CorrectAddress(){
try {
new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.IPv6, "xxx:xxx:xxx", 0);
} catch (Exception e){
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testIDNNotExceeds255CharsLimit(){
try {
new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.DOMAIN,
"παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" +
"παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" +
"παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή" +
"παράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμήπαράδειγμα.δοκιμή", 0);
} catch (Exception e){
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testValidPortRange(){
try {
new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.DOMAIN,
"παράδειγμα.δοκιμήπαράδει", -1);
} catch (Exception e){
assertTrue(e instanceof IllegalArgumentException);
}
try {
new SocksCmdRequest(SocksMessage.CmdType.BIND, SocksMessage.AddressType.DOMAIN,
"παράδειγμα.δοκιμήπαράδει", 65536);
} catch (Exception e){
assertTrue(e instanceof IllegalArgumentException);
}
}
}
| mheath/netty | codec-socks/src/test/java/io/netty/codec/socks/SocksCmdRequestTest.java |
45,881 | /****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package org.apache.james.core;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import java.util.stream.Stream;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import nl.jqno.equalsverifier.EqualsVerifier;
class MailAddressTest {
private static final String GOOD_LOCAL_PART = "\"quoted@local part\"";
private static final String GOOD_QUOTED_LOCAL_PART = "\"quoted@local part\"@james.apache.org";
private static final String GOOD_ADDRESS = "[email protected]";
private static final Domain GOOD_DOMAIN = Domain.of("james.apache.org");
private static Stream<Arguments> goodAddresses() {
return Stream.of(
GOOD_ADDRESS,
GOOD_QUOTED_LOCAL_PART,
"[email protected]",
"server-dev@[127.0.0.1]",
"[email protected]",
"\\[email protected]",
"[email protected]",
"[email protected]",
"user+mailbox/[email protected]",
"[email protected]",
"\"Abc@def\"@example.com",
"\"Fred Bloggs\"@example.com",
"\"Joe.\\Blow\"@example.com",
"!#$%&'*+-/=?^_`.{|}[email protected]")
.map(Arguments::of);
}
private static Stream<Arguments> badAddresses() {
return Stream.of(
"",
"server-dev",
"server-dev@",
"[]",
"server-dev@[]",
"server-dev@#",
"quoted [email protected]",
"quoted@[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected].",
"[email protected]",
"[email protected]",
"[email protected]",
"server-dev@#james.apache.org",
"server-dev@#123james.apache.org",
"server-dev@#-123.james.apache.org",
"server-dev@james. apache.org",
"server-dev@james\\.apache.org",
"server-dev@[300.0.0.1]",
"server-dev@[127.0.1]",
"server-dev@[0127.0.0.1]",
"server-dev@[127.0.1.1a]",
"server-dev@[127\\.0.1.1]",
"server-dev@#123",
"server-dev@#123.apache.org",
"server-dev@[127.0.1.1.1]",
"server-dev@[127.0.1.-1]",
"\"a..b\"@domain.com", // Javax.mail is unable to handle this so we better reject it
"server-dev\\[email protected]", // Javax.mail is unable to handle this so we better reject it
"[email protected]",
// According to wikipedia these addresses are valid but as javax.mail is unable
// to work with them we shall rather reject them (note that this is not breaking retro-compatibility)
"Loïc.Accentué@voilà.fr8",
"pelé@exemple.com",
"δοκιμή@παράδειγμα.δοκιμή",
"我買@屋企.香港",
"二ノ宮@黒川.日本",
"медведь@с-балалайкой.рф",
"संपर्क@डाटामेल.भारत")
.map(Arguments::of);
}
@ParameterizedTest
@MethodSource("goodAddresses")
void testGoodMailAddressString(String mailAddress) {
assertThatCode(() -> new MailAddress(mailAddress))
.doesNotThrowAnyException();
}
@ParameterizedTest
@MethodSource("goodAddresses")
void toInternetAddressShouldNoop(String mailAddress) throws Exception {
assertThat(new MailAddress(mailAddress).toInternetAddress())
.isNotEmpty();
}
@ParameterizedTest
@MethodSource("badAddresses")
void testBadMailAddressString(String mailAddress) {
Assertions.assertThatThrownBy(() -> new MailAddress(mailAddress))
.isInstanceOf(AddressException.class);
}
@Test
void testGoodMailAddressWithLocalPartAndDomain() {
assertThatCode(() -> new MailAddress("local-part", "domain"))
.doesNotThrowAnyException();
}
@Test
void testBadMailAddressWithLocalPartAndDomain() {
Assertions.assertThatThrownBy(() -> new MailAddress("local-part", "-domain"))
.isInstanceOf(AddressException.class);
}
@Test
void testMailAddressInternetAddress() {
assertThatCode(() -> new MailAddress(new InternetAddress(GOOD_QUOTED_LOCAL_PART)))
.doesNotThrowAnyException();
}
@Test
void testGetDomain() throws AddressException {
MailAddress a = new MailAddress(new InternetAddress(GOOD_ADDRESS));
assertThat(a.getDomain()).isEqualTo(GOOD_DOMAIN);
}
@Test
void testGetLocalPart() throws AddressException {
MailAddress a = new MailAddress(new InternetAddress(GOOD_QUOTED_LOCAL_PART));
assertThat(a.getLocalPart()).isEqualTo(GOOD_LOCAL_PART);
}
@Test
void testToString() throws AddressException {
MailAddress a = new MailAddress(new InternetAddress(GOOD_ADDRESS));
assertThat(a.toString()).isEqualTo(GOOD_ADDRESS);
}
@Test
void testToInternetAddress() throws AddressException {
InternetAddress b = new InternetAddress(GOOD_ADDRESS);
MailAddress a = new MailAddress(b);
assertThat(a.toInternetAddress()).contains(b);
assertThat(a.toString()).isEqualTo(GOOD_ADDRESS);
}
@Test
void testEqualsObject() throws AddressException {
MailAddress a = new MailAddress(GOOD_ADDRESS);
MailAddress b = new MailAddress(GOOD_ADDRESS);
assertThat(a).isNotNull().isEqualTo(b);
}
@Test
void equalsShouldReturnTrueWhenBothNullSender() {
assertThat(MailAddress.nullSender())
.isEqualTo(MailAddress.nullSender());
}
@SuppressWarnings("deprecation")
@Test
void getMailSenderShouldReturnNullSenderWhenNullSender() {
assertThat(MailAddress.getMailSender(MailAddress.NULL_SENDER_AS_STRING))
.isEqualTo(MailAddress.nullSender());
}
@SuppressWarnings("deprecation")
@Test
void getMailSenderShouldReturnParsedAddressWhenNotNullAddress() throws Exception {
assertThat(MailAddress.getMailSender(GOOD_ADDRESS))
.isEqualTo(new MailAddress(GOOD_ADDRESS));
}
@SuppressWarnings("deprecation")
@Test
void equalsShouldReturnFalseWhenOnlyFirstMemberIsANullSender() {
assertThat(MailAddress.getMailSender(GOOD_ADDRESS))
.isNotEqualTo(MailAddress.nullSender());
}
@SuppressWarnings("deprecation")
@Test
void equalsShouldReturnFalseWhenOnlySecondMemberIsANullSender() {
assertThat(MailAddress.nullSender())
.isNotEqualTo(MailAddress.getMailSender(GOOD_ADDRESS));
}
@Test
void shouldMatchBeanContract() {
EqualsVerifier.forClass(MailAddress.class)
.verify();
}
}
| linagora/james-project | core/src/test/java/org/apache/james/core/MailAddressTest.java |
45,882 | package android.util;
import java.util.regex.Pattern;
public class ColorPatterns {
public static final String ENG_IRI_CHAR = "a-zA-Z0-9";
public static final String GOOD_IRI_CHAR = "a-zA-Z0-9 -豈-﷏ﷰ-";
public static final String MEDIA_FORMAT_CHAR = "(MP3|MP2|APE|FLAC|OGG|WAV|WMA|AAC|MIDI|AMR|RA|M4A|MMF|SND|AU|AIFF|IMY|MKV|MOV|MP4|4K|AVI|WMV|ASF|TS|3GP|FLV|RMVB|RM|MPG|M2TS|VOB|DAT|WEBM|JPG|BMP|WBMP|PNG|GIF)";
public static final Pattern PHONE = Pattern.compile("(\\+[0-9]+[\\- \\.]*)?(\\([0-9]+\\)[\\- \\.]*)?([0-9][0-9\\-]+[0-9])");
public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL_EXPAND = "(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:inc|info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))";
public static final Pattern WEB_URL = Pattern.compile("((?:(ftp|http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?((?:(?:[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}\\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:inc|info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\_])|(?:\\%[a-fA-F0-9]{2})|([a-zA-Z0-9 -豈-﷏ﷰ-]+\\.(MP3|MP2|APE|FLAC|OGG|WAV|WMA|AAC|MIDI|AMR|RA|M4A|MMF|SND|AU|AIFF|IMY|MKV|MOV|MP4|4K|AVI|WMV|ASF|TS|3GP|FLV|RMVB|RM|MPG|M2TS|VOB|DAT|WEBM|JPG|BMP|WBMP|PNG|GIF)))*)?", 2);
private ColorPatterns() {
}
}
| dstmath/OppoFramework | A5_8_1_0/src/main/java/android/util/ColorPatterns.java |
45,883 | package aQute.tester.junit.platform.test;
import static aQute.junit.constants.TesterConstants.TESTER_CONTINUOUS;
import static aQute.junit.constants.TesterConstants.TESTER_CONTROLPORT;
import static aQute.junit.constants.TesterConstants.TESTER_NAMES;
import static aQute.junit.constants.TesterConstants.TESTER_PORT;
import static aQute.junit.constants.TesterConstants.TESTER_TRACE;
import static aQute.junit.constants.TesterConstants.TESTER_UNRESOLVED;
import static aQute.tester.test.utils.TestRunData.nameOf;
import static org.eclipse.jdt.internal.junit.model.ITestRunListener2.STATUS_FAILURE;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.assertj.core.api.Assertions;
import org.junit.AssumptionViolatedException;
import org.junit.ComparisonFailure;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.platform.commons.JUnitException;
import org.junit.platform.launcher.TestExecutionListener;
import org.opentest4j.AssertionFailedError;
import org.opentest4j.MultipleFailuresError;
import org.opentest4j.TestAbortedException;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.w3c.dom.Document;
import org.xmlunit.assertj.XmlAssert;
import aQute.launchpad.BundleBuilder;
import aQute.launchpad.LaunchpadBuilder;
import aQute.lib.io.IO;
import aQute.lib.xml.XML;
import aQute.tester.test.assertions.CustomAssertionError;
import aQute.tester.test.assertions.internal.CustomAssertionFailedError;
import aQute.tester.test.assertions.internal.CustomJUnit3ComparisonFailure;
import aQute.tester.test.assertions.internal.CustomJUnit4ComparisonFailure;
import aQute.tester.test.assertions.internal.CustomMultipleFailuresError;
import aQute.tester.test.utils.TestEntry;
import aQute.tester.test.utils.TestFailure;
import aQute.tester.test.utils.TestRunData;
import aQute.tester.test.utils.TestRunListener;
import aQute.tester.testbase.AbstractActivatorCommonTest;
import aQute.tester.testbase.AbstractActivatorTest;
import aQute.tester.testclasses.JUnit3Test;
import aQute.tester.testclasses.JUnit4Test;
import aQute.tester.testclasses.With1Error1Failure;
import aQute.tester.testclasses.With2Failures;
import aQute.tester.testclasses.junit.platform.JUnit3ComparisonTest;
import aQute.tester.testclasses.junit.platform.JUnit4AbortTest;
import aQute.tester.testclasses.junit.platform.JUnit4ComparisonTest;
import aQute.tester.testclasses.junit.platform.JUnit4Skipper;
import aQute.tester.testclasses.junit.platform.JUnit5AbortTest;
import aQute.tester.testclasses.junit.platform.JUnit5ContainerError;
import aQute.tester.testclasses.junit.platform.JUnit5ContainerFailure;
import aQute.tester.testclasses.junit.platform.JUnit5ContainerSkipped;
import aQute.tester.testclasses.junit.platform.JUnit5ContainerSkippedWithCustomDisplayName;
import aQute.tester.testclasses.junit.platform.JUnit5DisplayNameTest;
import aQute.tester.testclasses.junit.platform.JUnit5ParameterizedTest;
import aQute.tester.testclasses.junit.platform.JUnit5SimpleComparisonTest;
import aQute.tester.testclasses.junit.platform.JUnit5Skipper;
import aQute.tester.testclasses.junit.platform.JUnit5Test;
import aQute.tester.testclasses.junit.platform.JUnitComparisonSubclassTest;
import aQute.tester.testclasses.junit.platform.JUnitMixedComparisonTest;
import aQute.tester.testclasses.junit.platform.Mixed35Test;
import aQute.tester.testclasses.junit.platform.Mixed45Test;
import aQute.tester.testclasses.junit.platform.ParameterizedTesterNamesTest;
public class ActivatorJUnitPlatformTest extends AbstractActivatorCommonTest {
public ActivatorJUnitPlatformTest() {
super("aQute.tester.junit.platform.Activator", "biz.aQute.tester.junit-platform");
}
@Override
protected void createLP() {
builder.usingClassLoader(SERVICELOADER_MASK);
super.createLP();
}
@Test
public void multipleMixedTests_areAllRun_withJupiterTest() {
final ExitCode exitCode = runTests(JUnit3Test.class, JUnit4Test.class, JUnit5Test.class);
assertThat(exitCode.exitCode).as("exit code")
.isZero();
assertThat(testBundler.getCurrentThread(JUnit3Test.class)).as("junit3")
.isSameAs(Thread.currentThread());
assertThat(testBundler.getCurrentThread(JUnit4Test.class)).as("junit4")
.isSameAs(Thread.currentThread());
assertThat(testBundler.getCurrentThread(JUnit5Test.class)).as("junit5")
.isSameAs(Thread.currentThread());
}
@SuppressWarnings("unchecked")
@Test
public void multipleMixedTests_inASingleTestCase_areAllRun() {
final ExitCode exitCode = runTests(Mixed35Test.class, Mixed45Test.class);
assertThat(exitCode.exitCode).as("exit code")
.isZero();
assertThat(testBundler.getStatic(Mixed35Test.class, Set.class, "methods")).as("Mixed JUnit 3 & 5")
.containsExactlyInAnyOrder("testJUnit3", "junit5Test");
assertThat(testBundler.getStatic(Mixed45Test.class, Set.class, "methods")).as("Mixed JUnit 4 & 5")
.containsExactlyInAnyOrder("junit4Test", "junit5Test");
}
@Test
public void eclipseListener_reportsResults_acrossMultipleBundles() throws InterruptedException {
Class<?>[][] tests = {
{
With2Failures.class, JUnit4Test.class
}, {
With1Error1Failure.class, JUnit5Test.class
}
};
TestRunData result = runTestsEclipse(tests);
assertThat(result.getTestCount()).as("testCount")
.isEqualTo(9);
// @formatter:off
assertThat(result.getNameMap()
.keySet()).as("executed")
.contains(
nameOf(With2Failures.class),
nameOf(With2Failures.class, "test1"),
nameOf(With2Failures.class, "test2"),
nameOf(With2Failures.class, "test3"),
nameOf(JUnit4Test.class),
nameOf(JUnit4Test.class, "somethingElse"),
nameOf(With1Error1Failure.class),
nameOf(With1Error1Failure.class, "test1"),
nameOf(With1Error1Failure.class, "test2"),
nameOf(With1Error1Failure.class, "test3"),
nameOf(JUnit5Test.class, "somethingElseAgain"),
nameOf(testBundles.get(0)),
nameOf(testBundles.get(1))
);
assertThat(result).as("result")
.hasFailedTest(With2Failures.class, "test1", AssertionError.class)
.hasSuccessfulTest(With2Failures.class, "test2")
.hasFailedTest(With2Failures.class, "test3", CustomAssertionError.class)
.hasSuccessfulTest(JUnit4Test.class, "somethingElse")
.hasErroredTest(With1Error1Failure.class, "test1", RuntimeException.class)
.hasSuccessfulTest(With1Error1Failure.class, "test2")
.hasFailedTest(With1Error1Failure.class, "test3", AssertionError.class)
.hasSuccessfulTest(JUnit5Test.class, "somethingElseAgain")
;
// @formatter:on
}
@Test
public void eclipseListener_worksInContinuousMode_withControlSocket() throws Exception {
try (ServerSocket controlSock = new ServerSocket(0)) {
controlSock.setSoTimeout(10000);
int controlPort = controlSock.getLocalPort();
builder.set("launch.services", "true")
.set(TESTER_CONTINUOUS, "true")
// This value should be ignored
.set(TESTER_PORT, Integer.toString(controlPort - 2))
.set(TESTER_CONTROLPORT, Integer.toString(controlPort));
createLP();
addTestBundle(With2Failures.class, JUnit4Test.class);
runTester();
try (Socket sock = controlSock.accept()) {
InputStream inStr = sock.getInputStream();
DataOutputStream outStr = new DataOutputStream(sock.getOutputStream());
readWithTimeout(inStr);
TestRunListener listener = startEclipseJUnitListener();
outStr.writeInt(eclipseJUnitPort);
outStr.flush();
listener.waitForClientToFinish(10000);
TestRunData result = listener.getLatestRunData();
if (result == null) {
Assertions.fail("Result was null" + listener);
return;
}
assertThat(result.getTestCount()).as("testCount")
.isEqualTo(5);
// @formatter:off
assertThat(result.getNameMap()
.keySet()).as("executed")
.contains(
nameOf(With2Failures.class),
nameOf(With2Failures.class, "test1"),
nameOf(With2Failures.class, "test2"),
nameOf(With2Failures.class, "test3"),
nameOf(JUnit4Test.class),
nameOf(JUnit4Test.class, "somethingElse"),
nameOf(testBundles.get(0))
);
assertThat(result).as("result")
.hasFailedTest(With2Failures.class, "test1", AssertionError.class)
.hasSuccessfulTest(With2Failures.class, "test2")
.hasFailedTest(With2Failures.class, "test3", CustomAssertionError.class)
.hasSuccessfulTest(JUnit4Test.class, "somethingElse")
;
// @formatter:on
addTestBundle(With1Error1Failure.class, JUnit5Test.class);
readWithTimeout(inStr);
listener = startEclipseJUnitListener();
outStr.writeInt(eclipseJUnitPort);
outStr.flush();
listener.waitForClientToFinish(10000);
result = listener.getLatestRunData();
if (result == null) {
Assertions.fail("Eclipse didn't capture output from the second run");
return;
}
int i = 2;
assertThat(result.getTestCount()).as("testCount:" + i)
.isEqualTo(4);
// @formatter:off
assertThat(result.getNameMap()
.keySet()).as("executed:2")
.contains(
nameOf(With1Error1Failure.class),
nameOf(With1Error1Failure.class, "test1"),
nameOf(With1Error1Failure.class, "test2"),
nameOf(With1Error1Failure.class, "test3"),
nameOf(JUnit5Test.class, "somethingElseAgain"),
nameOf(testBundles.get(1))
);
assertThat(result).as("result:2")
.hasErroredTest(With1Error1Failure.class, "test1", RuntimeException.class)
.hasSuccessfulTest(With1Error1Failure.class, "test2")
.hasFailedTest(With1Error1Failure.class, "test3", AssertionError.class)
.hasSuccessfulTest(JUnit5Test.class, "somethingElseAgain")
;
// @formatter:on
}
}
}
@Test
public void eclipseListener_reportsComparisonFailures() throws InterruptedException {
Class<?>[] tests = {
JUnit3ComparisonTest.class, JUnit4ComparisonTest.class, JUnit5SimpleComparisonTest.class, JUnit5Test.class,
JUnitMixedComparisonTest.class
};
TestRunData result = runTestsEclipse(tests);
final String[] order = {
"1", "2", "3.1", "3.2", "3.4", "4"
};
// @formatter:off
assertThat(result).as("result")
.hasFailedTest(JUnit3ComparisonTest.class, "testComparisonFailure", junit.framework.ComparisonFailure.class, "expected", "actual")
.hasFailedTest(JUnit4ComparisonTest.class, "comparisonFailure", ComparisonFailure.class, "expected", "actual")
.hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class, "expected", "actual")
.hasFailedTest(JUnitMixedComparisonTest.class, "multipleComparisonFailure", MultipleFailuresError.class,
Stream.of(order).map(x -> "expected" + x).collect(Collectors.joining("\n\n")),
Stream.of(order).map(x -> "actual" + x).collect(Collectors.joining("\n\n"))
)
;
// @formatter:on
TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure"));
assertThat(f).as("emptyComparisonFailure")
.isNotNull();
if (f != null) {
assertThat(f.status).as("emptyComparisonFailure:status")
.isEqualTo(STATUS_FAILURE);
assertThat(f.expected).as("emptyComparisonFailure:expected")
.isNull();
assertThat(f.actual).as("emptyComparisonFailure:actual")
.isNull();
}
}
static class ActivatorJUnitPlatformTest_WithCustomAssertions extends AbstractActivatorTest {
public ActivatorJUnitPlatformTest_WithCustomAssertions() {
super("aQute.tester.junit.platform.Activator", "biz.aQute.tester.junit-platform");
}
// Needed to override this method so that we could create a bundle
// with the custom assertions in it that the test bundle could
// reference. If we reference them via the framework classloader,
// they will link to a different version of the JUnit 3/4 classes
// and so the code-under-test will not recognise the assertions
// as being subclasses of the JUnit 3/4 classes.
@Override
protected void createLP() {
builder.usingClassLoader(SERVICELOADER_MASK);
builder.excludeExport(CustomMultipleFailuresError.class.getPackage()
.getName());
super.createLP();
BundleBuilder bb = lp.bundle();
Stream
.of(CustomAssertionFailedError.class, CustomJUnit4ComparisonFailure.class,
CustomJUnit3ComparisonFailure.class, CustomMultipleFailuresError.class)
.forEach(clazz -> {
bb.addResourceWithCopy(clazz);
bb.exportPackage(clazz.getPackage()
.getName());
});
bb.start();
}
@Test
public void eclipseListener_reportsComparisonFailures_forSubclasses() throws InterruptedException {
Class<?>[] tests = {
JUnitComparisonSubclassTest.class
};
TestRunData result = runTestsEclipse(tests);
final String[] order = {
"1", "2", "3.1", "3.2", "3.4", "4"
};
// @formatter:off
assertThat(result).as("result")
.hasFailedTest(JUnitComparisonSubclassTest.class, "multipleComparisonFailure", CustomMultipleFailuresError.class,
Stream.of(order).map(x -> "expected" + x).collect(Collectors.joining("\n\n")),
Stream.of(order).map(x -> "actual" + x).collect(Collectors.joining("\n\n"))
)
;
// @formatter:on
}
@SuppressWarnings("removal")
@BeforeEach
public void setUp(TestInfo info) throws Exception {
this.info = info;
builder = new LaunchpadBuilder();
builder.bndrun(tester + ".bndrun")
.excludeExport("aQute.tester.bundle.*")
.excludeExport("org.junit*")
.excludeExport("junit.*");
setResultsDir();
if (DEBUG) {
builder.debug()
.set(TESTER_TRACE, "true");
}
lp = null;
oldManager = setExitToThrowExitCode();
}
@SuppressWarnings("removal")
@AfterEach
public void tearDown() {
IO.close(oldManager);
IO.close(lp);
IO.close(builder);
}
}
@Test
public void eclipseListener_reportsParameterizedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5ParameterizedTest.class);
TestEntry methodTest = result.getTest(JUnit5ParameterizedTest.class, "parameterizedMethod");
if (methodTest == null) {
Assertions.fail(
"Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, "parameterizedMethod"));
return;
}
assertThat(methodTest.parameterTypes).as("parameterTypes")
.containsExactly("java.lang.String", "float");
List<TestEntry> parameterTests = result.getChildrenOf(methodTest.testId)
.stream()
.map(x -> result.getById(x))
.collect(Collectors.toList());
assertThat(parameterTests.stream()
.map(x -> x.testName)).as("testNames")
.allMatch(x -> x.equals(nameOf(JUnit5ParameterizedTest.class, "parameterizedMethod")));
assertThat(parameterTests.stream()).as("dynamic")
.allMatch(x -> x.isDynamicTest);
assertThat(parameterTests.stream()
.map(x -> x.displayName)).as("displayNames")
.containsExactlyInAnyOrder("1 ==> param: 'one', param2: 1.0", "2 ==> param: 'two', param2: 2.0",
"3 ==> param: 'three', param2: 3.0", "4 ==> param: 'four', param2: 4.0",
"5 ==> param: 'five', param2: 5.0");
Optional<TestEntry> test4 = parameterTests.stream()
.filter(x -> x.displayName.startsWith("4 ==>"))
.findFirst();
if (!test4.isPresent()) {
check(() -> Assertions.fail("Couldn't find test result for parameter 4"));
} else {
assertThat(parameterTests.stream()
.filter(x -> result.getFailure(x.testId) != null)).as("failures")
.containsExactly(test4.get());
}
}
@Test
public void eclipseListener_reportsMisconfiguredParameterizedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5ParameterizedTest.class);
TestEntry methodTest = result.getTest(JUnit5ParameterizedTest.class, "misconfiguredMethod");
if (methodTest == null) {
Assertions.fail(
"Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, "misconfiguredMethod"));
return;
}
TestFailure failure = result.getFailure(methodTest.testId);
if (failure == null) {
check(() -> Assertions.fail("Expecting method:\n%s\nto have failed", methodTest));
} else {
assertThat(failure.trace).as("trace")
.startsWith(
"org.junit.platform.commons.PreconditionViolationException: Could not find factory method [unknownMethod]");
}
}
@Test
public void eclipseListener_reportsCustomNames_withOddCharacters() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5DisplayNameTest.class);
final String[] methodList = {
"test1", "testWithNonASCII", "testWithNonLatin"
};
final String[] displayList = {
// "Test 1", "Prüfung 2", "Δοκιμή 3"
"Test 1", "Pr\u00fcfung 2", "\u0394\u03bf\u03ba\u03b9\u03bc\u03ae 3"
};
for (int i = 0; i < methodList.length; i++) {
final String method = methodList[i];
final String display = displayList[i];
TestEntry methodTest = result.getTest(JUnit5DisplayNameTest.class, method);
if (methodTest == null) {
check(() -> Assertions
.fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, method)));
continue;
}
assertThat(methodTest.displayName).as(String.format("[%d] %s", i, method))
.isEqualTo(display);
}
}
@Test
public void eclipseListener_reportsSkippedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5Skipper.class, JUnit5ContainerSkipped.class,
JUnit5ContainerSkippedWithCustomDisplayName.class, JUnit4Skipper.class);
assertThat(result).as("result")
.hasSkippedTest(JUnit5Skipper.class, "disabledTest", "with custom message")
.hasSkippedTest(JUnit5ContainerSkipped.class, "with another message")
.hasSkippedTest(JUnit5ContainerSkipped.class, "disabledTest2",
"ancestor \"JUnit5ContainerSkipped\" was skipped")
.hasSkippedTest(JUnit5ContainerSkipped.class, "disabledTest3",
"ancestor \"JUnit5ContainerSkipped\" was skipped")
.hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "with a third message")
.hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "disabledTest2",
"ancestor \"Skipper Class\" was skipped")
.hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "disabledTest3",
"ancestor \"Skipper Class\" was skipped")
.hasSkippedTest(JUnit4Skipper.class, "disabledTest", "This is a test");
}
@Test
public void eclipseListener_reportsAbortedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5AbortTest.class, JUnit4AbortTest.class);
assertThat(result).as("result")
.hasAbortedTest(JUnit5AbortTest.class, "abortedTest",
new TestAbortedException("Assumption failed: I just can't go on"))
.hasAbortedTest(JUnit4AbortTest.class, "abortedTest",
new AssumptionViolatedException("Let's get outta here"));
}
@Test
public void eclipseListener_handlesNoEnginesGracefully() throws Exception {
try (LaunchpadBuilder builder = new LaunchpadBuilder()) {
IO.close(this.builder);
builder.bndrun("no-engines.bndrun")
.excludeExport("org.junit*")
.excludeExport("junit*");
this.builder = builder;
setResultsDir();
TestRunData result = runTestsEclipse(JUnit5AbortTest.class, JUnit4AbortTest.class);
assertThat(result).hasErroredTest("Initialization Error",
new JUnitException("Couldn't find any registered TestEngines"));
}
}
@Test
public void eclipseListener_handlesNoJUnit3Gracefully() throws Exception {
builder.excludeExport("junit.framework");
Class<?>[] tests = {
JUnit4ComparisonTest.class, JUnit5Test.class, JUnit5SimpleComparisonTest.class
};
TestRunData result = runTestsEclipse(tests);
assertThat(result).as("result")
.hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class,
"expected", "actual");
TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure"));
assertThat(f).as("emptyComparisonFailure")
.isNotNull();
if (f != null) {
assertThat(f.status).as("emptyComparisonFailure:status")
.isEqualTo(STATUS_FAILURE);
assertThat(f.expected).as("emptyComparisonFailure:expected")
.isNull();
assertThat(f.actual).as("emptyComparisonFailure:actual")
.isNull();
}
}
@Test
public void eclipseListener_handlesNoJUnit4Gracefully() throws Exception {
try (LaunchpadBuilder builder = new LaunchpadBuilder()) {
IO.close(this.builder);
builder.debug();
builder.bndrun("no-vintage-engine.bndrun")
.excludeExport("aQute.tester.bundle.*")
.excludeExport("org.junit*")
.excludeExport("junit*");
this.builder = builder;
setResultsDir();
Class<?>[] tests = {
JUnit3ComparisonTest.class, JUnit5Test.class, JUnit5SimpleComparisonTest.class
};
TestRunData result = runTestsEclipse(tests);
assertThat(result).as("result")
.hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class,
"expected", "actual");
TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure"));
assertThat(f).as("emptyComparisonFailure")
.isNotNull();
if (f != null) {
assertThat(f.status).as("emptyComparisonFailure:status")
.isEqualTo(STATUS_FAILURE);
assertThat(f.expected).as("emptyComparisonFailure:expected")
.isNull();
assertThat(f.actual).as("emptyComparisonFailure:actual")
.isNull();
}
}
}
@Test
public void testerUnresolvedTrue_isPassedThroughToBundleEngine() {
builder.set(TESTER_UNRESOLVED, "true");
AtomicReference<Bundle> bundleRef = new AtomicReference<>();
TestRunData result = runTestsEclipse(() -> {
bundleRef.set(bundle().importPackage("some.unknown.package")
.install());
}, JUnit3Test.class, JUnit4Test.class);
assertThat(result).hasSuccessfulTest("Unresolved bundles");
}
@Test
public void testerUnresolvedFalse_isPassedThroughToBundleEngine() {
builder.set(TESTER_UNRESOLVED, "false");
AtomicReference<Bundle> bundleRef = new AtomicReference<>();
TestRunData result = runTestsEclipse(() -> {
bundleRef.set(bundle().importPackage("some.unknown.package")
.install());
}, JUnit3Test.class, JUnit4Test.class);
assertThat(result.getNameMap()
.get("Unresolved bundles")).isNull();
}
@Test
public void testerNames_withParameters_isHonouredByTester() {
builder.set(TESTER_NAMES,
"'" + ParameterizedTesterNamesTest.class.getName() + ":parameterizedMethod(java.lang.String,float)'");
runTests(0, JUnit3Test.class, JUnit4Test.class, ParameterizedTesterNamesTest.class);
assertThat(testBundler.getCurrentThread(JUnit3Test.class)).as("JUnit3 thread")
.isNull();
assertThat(testBundler.getCurrentThread(JUnit4Test.class)).as("JUnit4 thread")
.isNull();
assertThat(testBundler.getInteger("countParameterized", ParameterizedTesterNamesTest.class))
.as("parameterizedMethod")
.isEqualTo(5);
assertThat(testBundler.getInteger("countOther", ParameterizedTesterNamesTest.class)).as("countOther")
.isEqualTo(0);
}
@Test
public void xmlReporter_generatesCompleteXmlFile() throws Exception {
final ExitCode exitCode = runTests(JUnit3Test.class, With1Error1Failure.class, With2Failures.class);
final String fileName = "TEST-" + testBundle.getSymbolicName() + "-" + testBundle.getVersion() + ".xml";
File xmlFile = getResultsDir().resolve(fileName)
.toFile();
Assertions.assertThat(xmlFile)
.as("xmlFile")
.exists();
AtomicReference<Document> docContainer = new AtomicReference<>();
Assertions.assertThatCode(() -> {
DocumentBuilderFactory dbFactory = XML.newDocumentBuilderFactory();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
docContainer.set(dBuilder.parse(xmlFile));
})
.doesNotThrowAnyException();
Document doc = docContainer.get();
XmlAssert.assertThat(doc)
.nodesByXPath("/testsuite")
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testSuite() + "/testcase")
.hasSize(7);
XmlAssert.assertThat(doc)
.nodesByXPath(testCase(JUnit3Test.class, "testSomething"))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseError(With1Error1Failure.class, "test1", RuntimeException.class))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCase(With1Error1Failure.class, "test2"))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseFailure(With1Error1Failure.class, "test3", AssertionError.class))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseFailure(With2Failures.class, "test1", AssertionError.class))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCase(With2Failures.class, "test2"))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseFailure(With2Failures.class, "test3", CustomAssertionError.class))
.hasSize(1);
}
// Unlike JUnit 4, Jupiter skips the tests when the parent container
// fails and does not report the children as test failures.
@Test
public void exitCode_countsJupiterContainerErrorsAndFailures() {
runTests(2, JUnit5ContainerFailure.class, JUnit5ContainerError.class);
}
public static class ListenerGenerator implements BundleActivator, InvocationHandler {
List<String> invocations;
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
if (method.getDeclaringClass()
.equals(TestExecutionListener.class)) {
invocations.add(method.getName());
}
return null;
}
ServiceRegistration<TestExecutionListener> reg;
@Override
public void start(BundleContext context) throws Exception {
TestExecutionListener listener = (TestExecutionListener) Proxy
.newProxyInstance(ListenerGenerator.class.getClassLoader(), new Class<?>[] {
TestExecutionListener.class
}, this);
invocations = new ArrayList<>();
reg = context.registerService(TestExecutionListener.class, listener, null);
}
@Override
public void stop(BundleContext context) throws Exception {
reg.unregister();
}
}
@Test
public void testListeners_areInvoked() throws Exception {
AtomicReference<Bundle> bRef = new AtomicReference<>();
final ExitCode exitCode = runTests(() -> {
Bundle b = lp.bundle()
.addResourceWithCopy(ListenerGenerator.class)
.bundleActivator(ListenerGenerator.class.getName())
.importPackage("org.junit.platform.engine")
.importPackage("org.junit.platform.engine.reporting")
.importPackage("*")
.start();
bRef.set(b);
}, JUnit3Test.class);
assertThat(exitCode.exitCode).as("exit code")
.isZero();
BundleContext context = bRef.get()
.getBundleContext();
ServiceReference<?> ref = context.getServiceReference(TestExecutionListener.class);
Object listener = context.getService(ref);
Object invocationHandler = Proxy.getInvocationHandler(listener);
Class<?> listenerGenerator = invocationHandler.getClass();
Field f = listenerGenerator.getDeclaredField("invocations");
f.setAccessible(true);
@SuppressWarnings("unchecked")
List<String> methods = (List<String>) f.get(invocationHandler);
assertThat(methods).containsExactly("testPlanExecutionStarted", "executionStarted", "executionStarted",
"executionStarted", "executionStarted", "executionStarted", "executionFinished", "executionFinished",
"executionFinished", "executionFinished", "executionFinished", "testPlanExecutionFinished");
}
}
| bndtools/bnd | biz.aQute.tester.test/test/aQute/tester/junit/platform/test/ActivatorJUnitPlatformTest.java |
45,884 | // SPDX-FileCopyrightText: 2020 Paul Schaub <[email protected]>, 2021 Flowcrypt a.s.
//
// SPDX-License-Identifier: Apache-2.0
package org.pgpainless.key;
import org.junit.jupiter.api.Test;
import org.pgpainless.key.util.UserId;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class UserIdTest {
@Test
public void throwForNullName() {
assertThrows(IllegalArgumentException.class, () -> UserId.newBuilder().withName(null));
}
@Test
public void throwForNullComment() {
assertThrows(IllegalArgumentException.class, () -> UserId.newBuilder().withComment(null));
}
@Test
public void throwForNullEmail() {
assertThrows(IllegalArgumentException.class, () -> UserId.newBuilder().withEmail(null));
}
@Test
public void testFormatOnlyName() {
assertEquals(
"Juliet Capulet",
UserId.newBuilder().withName("Juliet Capulet")
.build().toString());
}
@Test
public void testFormatNameAndComment() {
assertEquals(
"Juliet Capulet (from the play)",
UserId.newBuilder().withName("Juliet Capulet")
.withComment("from the play")
.noEmail().build().toString());
}
@Test
public void testFormatNameCommentAndMail() {
assertEquals("Juliet Capulet (from the play) <[email protected]>",
UserId.newBuilder().withName("Juliet Capulet")
.withComment("from the play")
.withEmail("[email protected]")
.build()
.toString());
}
@Test
public void testFormatNameAndEmail() {
assertEquals("Juliet Capulet <[email protected]>",
UserId.newBuilder().withName("Juliet Capulet")
.noComment()
.withEmail("[email protected]")
.build()
.toString());
}
@Test
public void throwIfOnlyEmailEmailNull() {
assertThrows(IllegalArgumentException.class, () -> UserId.onlyEmail(null));
}
@Test
public void testNameAndEmail() {
UserId userId = UserId.nameAndEmail("Maurice Moss", "[email protected]");
assertEquals("Maurice Moss <[email protected]>", userId.toString());
}
@Test
void testBuilderWithName() {
final UserId userId = UserId.newBuilder().withName("John Smith").build();
assertEquals("John Smith", userId.getName());
assertNull(userId.getComment());
assertNull(userId.getEmail());
}
@Test
void testBuilderWithComment() {
final UserId userId = UserId.newBuilder().withComment("Sales Dept.").build();
assertNull(userId.getName());
assertEquals("Sales Dept.", userId.getComment());
assertNull(userId.getEmail());
}
@Test
void testBuilderWithEmail() {
final UserId userId = UserId.newBuilder().withEmail("[email protected]").build();
assertNull(userId.getName());
assertNull(userId.getComment());
assertEquals("[email protected]", userId.getEmail());
}
@Test
void testBuilderWithAll() {
final UserId userId = UserId.newBuilder().withEmail("[email protected]")
.withName("John Smith")
.withEmail("[email protected]")
.withComment("Sales Dept.").build();
assertEquals("John Smith", userId.getName());
assertEquals("Sales Dept.", userId.getComment());
assertEquals("[email protected]", userId.getEmail());
}
@Test
void testBuilderNoName() {
final UserId.Builder builder = UserId.newBuilder()
.withEmail("[email protected]")
.withName("John Smith")
.withComment("Sales Dept.").build().toBuilder();
final UserId userId = builder.noName().build();
assertNull(userId.getName());
assertEquals("Sales Dept.", userId.getComment());
assertEquals("[email protected]", userId.getEmail());
}
@Test
void testBuilderNoComment() {
final UserId.Builder builder = UserId.newBuilder()
.withEmail("[email protected]")
.withName("John Smith")
.withComment("Sales Dept.").build().toBuilder();
final UserId userId = builder.noComment().build();
assertEquals("John Smith", userId.getName());
assertNull(userId.getComment());
assertEquals("[email protected]", userId.getEmail());
}
@Test
void testBuilderNoEmail() {
final UserId.Builder builder = UserId.newBuilder()
.withEmail("[email protected]")
.withName("John Smith")
.withComment("Sales Dept.").build().toBuilder();
final UserId userId = builder.noEmail().build();
assertEquals("John Smith", userId.getName());
assertEquals("Sales Dept.", userId.getComment());
assertNull(userId.getEmail());
}
@Test
void testEmailOnlyFormatting() {
final UserId userId = UserId.onlyEmail("[email protected]");
assertEquals("[email protected]", userId.toString());
}
@Test
void testEmptyNameAndValidEmailFormatting() {
final UserId userId = UserId.nameAndEmail("", "[email protected]");
assertEquals("[email protected]", userId.toString());
assertEquals("[email protected]", userId.asString(false));
assertEquals("[email protected]", userId.asString(true));
}
@Test
void testEmptyNameAndEmptyCommentAndValidEmailFormatting() {
final UserId userId = UserId.newBuilder()
.withComment("")
.withName("")
.withEmail("[email protected]")
.build();
assertEquals(" () <[email protected]>", userId.toString());
assertEquals(" () <[email protected]>", userId.asString(false));
assertEquals("[email protected]", userId.asString(true));
}
@Test
void testEqualsWithDifferentCaseEmails() {
final String name = "John Smith";
final String comment = "Sales Dept.";
final String email = "[email protected]";
final String upperEmail = email.toUpperCase();
final UserId userId1 = UserId.newBuilder().withComment(comment).withName(name).withEmail(email).build();
final UserId userId2 = UserId.newBuilder().withComment(comment).withName(name).withEmail(upperEmail).build();
assertEquals(userId1, userId2);
}
@Test
void testNotEqualWithDifferentNames() {
final String name1 = "John Smith";
final String name2 = "Don Duck";
final String comment = "Sales Dept.";
final String email = "[email protected]";
final UserId userId1 = UserId.newBuilder().withComment(comment).withName(name1).withEmail(email).build();
final UserId userId2 = UserId.newBuilder().withComment(comment).withName(name2).withEmail(email).build();
assertNotEquals(userId1, userId2);
}
@Test
void testNotEqualWithDifferentComments() {
final String name = "John Smith";
final String comment1 = "Sales Dept.";
final String comment2 = "Legal Dept.";
final String email = "[email protected]";
final UserId userId1 = UserId.newBuilder().withComment(comment1).withName(name).withEmail(email).build();
final UserId userId2 = UserId.newBuilder().withComment(comment2).withName(name).withEmail(email).build();
assertNotEquals(userId1, userId2);
}
}
| farnulfo/pgpainless | pgpainless-core/src/test/java/org/pgpainless/key/UserIdTest.java |
45,885 | /*
* <summary></summary>
* <author>He Han</author>
* <email>[email protected]</email>
* <create-date>16/3/18 AM11:51</create-date>
*
* <copyright file="URLTokenizer.java" company="码农场">
* Copyright (c) 2008-2016, 码农场. All Right Reserved, http://www.hankcs.com/
* This source is subject to Hankcs. Please contact Hankcs to get more information.
* </copyright>
*/
package com.hankcs.hanlp.tokenizer;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.corpus.tag.Nature;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.common.Term;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 可以识别URL的分词器
* @author hankcs
*/
public class URLTokenizer
{
/**
* 预置分词器
*/
public static final Segment SEGMENT = HanLP.newSegment();
private static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(((([a-zA-Z0-9][a-zA-Z0-9\\-]*)*[a-zA-Z0-9]\\.)+((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?");
/**
* 分词
* @param text 文本
* @return 分词结果
*/
public static List<Term> segment(String text)
{
List<Term> termList = new LinkedList<Term>();
Matcher matcher = WEB_URL.matcher(text);
int begin = 0;
int end;
while (matcher.find())
{
end = matcher.start();
termList.addAll(SEGMENT.seg(text.substring(begin, end)));
termList.add(new Term(matcher.group(), Nature.xu));
begin = matcher.end();
}
if (begin < text.length()) termList.addAll(SEGMENT.seg(text.substring(begin)));
return termList;
}
}
| adofsauron/HanLP | src/main/java/com/hankcs/hanlp/tokenizer/URLTokenizer.java |
45,886 | package com.xiaomi.scanner.module.code.codec;
import android.content.Context;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import com.google.zxing.Result;
import com.google.zxing.client.result.AddressBookParsedResult;
import com.google.zxing.client.result.VCardResultParser;
import com.xiaomi.scanner.R;
import com.xiaomi.scanner.module.code.zxing.VCard;
import com.xiaomi.scanner.module.code.zxing.WiFiUtil;
import com.xiaomi.scanner.settings.FeatureManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QRCodeMatcher {
private static final Pattern CARD = Pattern.compile("(card\\s*:.*)");
private static final Pattern CARDHEAD = Pattern.compile("\\s*(CARD|mecard)\\s*:\\s*");
public static final String INTENT_CARD_KEY_BIRTH = "birth";
private static String INTENT_INSERT_WEBSITE = "website";
private static final Pattern MARKET = Pattern.compile("(market\\s*:\\/\\/.*)");
private static final Pattern MECARD = Pattern.compile("(mecard\\s*:.*)");
private static final Pattern MECARDHEAD = Pattern.compile("\\s*(MECARD|mecard)\\s*:\\s*");
private static final Pattern MECARDSPLIT = Pattern.compile("([a-zA-Z]{1,6}\\s*:[^;]+);");
private static final Pattern MIRACAST_BOX = Pattern.compile("(http:\\/\\/weixin.qq.com\\/r\\/P3XO1lDE8w2MrRS19yAt\\/info\\?miracast_tvmac.*)");
public static final String MIRACAST_PARAM_MAC = "miracast_tvmac";
public static final String MIRACAST_PARAM_NAME = "miracast_tvname";
private static final Pattern MIRACAST_TV = Pattern.compile("(?:https?:\\/\\/qmirror\\.sys\\.tv\\.mi\\.com\\/\\?(?:.*&)?miracast_tvmac=.*)|(?:https?:\\/\\/weixin\\.qq\\.com\\/r\\/N3Xv96DE_-2EreSU9yAl(\\/info)?\\?miracast_tvmac.*)");
private static final Pattern NUMBER = Pattern.compile("^[0-9]*$");
private static final Pattern PAYTM_ALPHANUMERIC = Pattern.compile("^\\p{Alnum}{24}$");
private static final Pattern PAYTM_DIGIT = Pattern.compile("^\\d{6}");
private static final Pattern PHONE = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
private static final Pattern VCARD = Pattern.compile("^BEGIN:VCARD(.|\n)*END:VCARD$");
private static final VCardResultParser VCARDPARSER = new VCardResultParser();
private static final Pattern WEB_URL = Pattern.compile("(?:(?:((http|https|rtsp)):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(?:(?:[a-zA-Z0-9 -豈-﷏ﷰ-][a-zA-Z0-9 -豈-﷏ﷰ-\\-]{0,64}\\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\\:\\d{1,5})?)(?:\\/(?:(?:[a-zA-Z0-9 -豈-﷏ﷰ-\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?(?:\\b|$)");
private static final Pattern WIFI = Pattern.compile("(WIFI\\s*:.*)");
private static final Pattern WIFIHEAD = Pattern.compile("WIFI\\s*:\\s*");
private static final Pattern WIFISPLIT = Pattern.compile("([a-zA-Z]{1,2}\\s*:[^;]+);");
private ArrayList<VCard> mCards = new ArrayList();
public static QRCodeType match(String original) {
original = original.trim();
String lowerCase = original.toLowerCase();
if (VCARD.matcher(original).matches()) {
return QRCodeType.VCARD;
}
if (MIRACAST_BOX.matcher(original).matches() || MIRACAST_TV.matcher(original).matches()) {
return QRCodeType.MIRACAST;
}
if (WEB_URL.matcher(lowerCase).matches()) {
return QRCodeType.WEB_URL;
}
Matcher match = MARKET.matcher(lowerCase);
if (match.find() && match.start() == 0) {
return QRCodeType.MARKET;
}
match = MECARD.matcher(lowerCase);
if (match.find() && match.start() == 0) {
return QRCodeType.MECARD;
}
match = CARD.matcher(lowerCase);
if (match.find() && match.start() == 0) {
return QRCodeType.CARD;
}
if (VCARDPARSER.parse(new Result(original, null, null, null)) != null) {
return QRCodeType.VCARD;
}
match = WIFI.matcher(original);
if (match.find() && match.start() == 0) {
return QRCodeType.WIFI;
}
if (PAYTM_ALPHANUMERIC.matcher(original).matches() && FeatureManager.isPaytmAvailable() && PAYTM_DIGIT.matcher(original).find()) {
return QRCodeType.PAYTM;
}
return QRCodeType.TEXT;
}
public ArrayList<VCard> contactsCardSpliter(String s, QRCodeType type, Context context) {
if (type == QRCodeType.MECARD || type == QRCodeType.CARD) {
return meCardSpliter(type, s, context);
}
if (type == QRCodeType.VCARD) {
return vCardSpliter(s, context);
}
return null;
}
public static boolean isNumber(String number) {
return NUMBER.matcher(number).matches();
}
private ArrayList<VCard> vCardSpliter(String s, Context context) {
AddressBookParsedResult vcard = VCARDPARSER.parse(new Result(s, null, null, null));
if (vcard != null) {
if (vcard.getNames() != null) {
findVcardValue("N", vcard.getNames(), context);
}
if (vcard.getNicknames() != null) {
findVcardValue("NICKNAME", vcard.getNicknames(), context);
}
if (vcard.getPhoneNumbers() != null) {
findVcardValue("TEL", vcard.getPhoneNumbers(), context);
}
if (vcard.getEmails() != null) {
findVcardValue("EMAIL", vcard.getEmails(), context);
}
if (vcard.getURLs() != null) {
findVcardValue("URL", vcard.getURLs(), context);
}
if (vcard.getAddresses() != null) {
findVcardValue("ADR", vcard.getAddresses(), context);
}
if (!TextUtils.isEmpty(vcard.getOrg())) {
this.mCards.add(getNameByKey("ORG", vcard.getOrg(), context));
}
if (!TextUtils.isEmpty(vcard.getTitle())) {
this.mCards.add(getNameByKey("TIL", vcard.getTitle(), context));
}
if (!TextUtils.isEmpty(vcard.getBirthday())) {
this.mCards.add(getNameByKey("BDAY", vcard.getBirthday(), context));
}
if (!TextUtils.isEmpty(vcard.getNote())) {
this.mCards.add(getNameByKey("NOTE", vcard.getNote(), context));
}
}
return this.mCards;
}
private ArrayList<VCard> findVcardValue(String key, String[] values, Context context) {
for (int i = 0; i < values.length; i++) {
if (!TextUtils.isEmpty(values[i])) {
VCard card = getNameByKey(key, values[i], context);
if (!(card == null || this.mCards.contains(card))) {
this.mCards.add(card);
}
}
}
return this.mCards;
}
private ArrayList<VCard> meCardSpliter(QRCodeType type, String s, Context context) {
Matcher head;
if (this.mCards == null) {
this.mCards = new ArrayList();
}
if (type == QRCodeType.MECARD) {
head = MECARDHEAD.matcher(s);
} else {
head = CARDHEAD.matcher(s);
}
if (head.find()) {
Matcher split = MECARDSPLIT.matcher(s.substring(head.end()));
while (split.find()) {
String pair = split.group(0);
if (pair != null) {
int index = pair.indexOf(58);
VCard card = getNameByKey(pair.substring(0, index).toUpperCase().trim(), pair.substring(index + 1, pair.length() - 1), context);
if (!this.mCards.contains(card)) {
this.mCards.add(card);
}
}
}
}
return this.mCards;
}
private VCard parsePhone(String value, Context context) {
String name = context.getResources().getString(R.string.phone);
String key = "phone";
VCard card = findVCardBykey(key);
if (card == null) {
return new VCard(key, name, value, isPhoneNumber(value));
}
card.addValue(value);
return card;
}
private VCard parseEmail(String value, Context context) {
String name = context.getResources().getString(R.string.email);
Map<String, String> type = new HashMap();
String key = NotificationCompat.CATEGORY_EMAIL;
VCard card = findVCardBykey(key);
if (card == null) {
return new VCard(key, name, value, false);
}
card.addValue(value);
return card;
}
private VCard getNameByKey(String key, String value, Context context) {
if (key.equalsIgnoreCase("N") || key.equalsIgnoreCase("NAME")) {
return new VCard("name", context.getResources().getString(R.string.name), value, false);
} else if (key.equalsIgnoreCase("NICKNAME")) {
return new VCard("data1", context.getResources().getString(R.string.nickname), value, false);
} else if (key.equalsIgnoreCase("TEL")) {
return parsePhone(value, context);
} else {
if (key.equalsIgnoreCase("EMAIL") || key.equalsIgnoreCase("EM")) {
return parseEmail(value, context);
}
if (key.equalsIgnoreCase("URL") || key.equalsIgnoreCase("DIV")) {
return new VCard(INTENT_INSERT_WEBSITE, context.getResources().getString(R.string.web), value, false);
} else if (key.equalsIgnoreCase("ADR")) {
return new VCard("postal", context.getResources().getString(R.string.address), value, false);
} else if (key.equalsIgnoreCase("ORG")) {
return new VCard("company", context.getResources().getString(R.string.company), value, false);
} else if (key.equalsIgnoreCase("TIL") || key.equalsIgnoreCase("TITLE")) {
return new VCard("job_title", context.getResources().getString(R.string.title), value, false);
} else if (key.equalsIgnoreCase("BDAY")) {
return new VCard(INTENT_CARD_KEY_BIRTH, context.getResources().getString(R.string.birthday), value, false);
} else if (!key.equalsIgnoreCase("NOTE")) {
return null;
} else {
return new VCard("notes", context.getResources().getString(R.string.note), value, false);
}
}
}
private VCard findVCardBykey(String key) {
Iterator it = this.mCards.iterator();
while (it.hasNext()) {
VCard card = (VCard) it.next();
if (card != null && card.getKey() != null && card.getKey().equalsIgnoreCase(key)) {
return card;
}
}
return null;
}
public static HashMap<String, String> wifiSpliter(String s) {
HashMap<String, String> map = new HashMap();
Matcher head = WIFIHEAD.matcher(s);
if (head.find()) {
Matcher split = WIFISPLIT.matcher(s.substring(head.end()));
while (split.find()) {
String pair = split.group(0);
if (pair != null) {
int index = pair.indexOf(58);
map.put(pair.substring(0, index).toUpperCase().trim(), WiFiUtil.removeDoubleQuotes(pair.substring(index + 1, pair.length() - 1)));
}
}
}
return map;
}
private static boolean isPhoneNumber(String phone) {
return PHONE.matcher(phone).matches();
}
}
| XEonAX/ANXMiuiApps | src/ANXScanner/sources/com/xiaomi/scanner/module/code/codec/QRCodeMatcher.java |
45,887 | package com.crumby.lib.widget.firstparty.omnibar;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import com.crumby.Analytics;
import com.crumby.BusProvider;
import com.crumby.impl.crumby.UnsupportedUrlFragment;
import com.crumby.lib.events.UrlChangeEvent;
import com.crumby.lib.router.FragmentIndex;
import com.crumby.lib.router.FragmentLink;
import com.crumby.lib.router.FragmentRouter;
import com.squareup.otto.Bus;
import java.util.HashSet;
import java.util.Set;
public class FragmentSuggestions
extends LinearLayout
implements View.OnClickListener
{
private BreadcrumbContainer breadcrumbContainer;
private boolean searchGalleries;
private Set<String> suggestionIds;
int visible;
public FragmentSuggestions(Context paramContext)
{
super(paramContext);
}
public FragmentSuggestions(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
}
public FragmentSuggestions(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(paramContext, paramAttributeSet, paramInt);
}
private void addSearchSuggestion(String paramString)
{
if (paramString.equals("")) {
return;
}
if ((!paramString.matches("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?((?:(?:[a-zA-Z0-9 -豈-﷏ﷰ-][a-zA-Z0-9 -豈-﷏ﷰ-\\-]{0,64}\\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9 -豈-﷏ﷰ-\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?(?:\\b|$)")) && (!paramString.contains("?")) && (!paramString.contains("crumby://")))
{
this.searchGalleries = true;
addSuggestionWithNoBaseUrl("Search All Galleries for \"" + paramString + "\"", " " + paramString, getResources().getDrawable(2130837640));
return;
}
this.searchGalleries = false;
}
private FragmentSuggestion addSuggestion(FragmentLink paramFragmentLink, Drawable paramDrawable)
{
if (this.visible >= getChildCount()) {
return null;
}
int i = this.visible;
this.visible = (i + 1);
FragmentSuggestion localFragmentSuggestion = (FragmentSuggestion)getChildAt(i);
localFragmentSuggestion.setImage(paramDrawable);
localFragmentSuggestion.setFragmentLink(paramFragmentLink);
return localFragmentSuggestion;
}
private FragmentSuggestion addSuggestion(String paramString1, String paramString2, String paramString3)
{
return addSuggestion(new FragmentLink(paramString1, paramString2, paramString3, 0), null);
}
private FragmentSuggestion addSuggestionWithNoBaseUrl(String paramString1, String paramString2, Drawable paramDrawable)
{
paramString1 = new FragmentLink(paramString1, paramString2, null, 0);
paramString1.setHideBaseUrl(true);
paramString1.setMandatory(true);
return addSuggestion(paramString1, paramDrawable);
}
public void appendFinal(String paramString1, String paramString2, boolean paramBoolean)
{
FragmentIndex localFragmentIndex = FragmentRouter.INSTANCE.getGalleryFragmentIndexByUrl(paramString1);
int j = 0;
int i;
if (localFragmentIndex != null)
{
if (localFragmentIndex.getFragmentClass().equals(UnsupportedUrlFragment.class)) {
break label95;
}
if (!paramBoolean) {
break label89;
}
i = j;
if (this.suggestionIds.contains(paramString1)) {
break label78;
}
paramString2 = addSuggestion("Favorite?", paramString1, paramString2);
if (paramString2 != null) {
break label65;
}
}
for (;;)
{
return;
label65:
paramString2.setHideBackground(true);
paramString2.notFavoritedYet();
i = j;
label78:
while (i != 0)
{
appendTryParse(paramString1);
return;
label89:
i = 1;
continue;
label95:
i = 1;
}
}
}
/* Error */
public void appendFragmentSuggestions(String paramString, java.util.List<FragmentLink> paramList)
{
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_2
// 3: invokeinterface 173 1 0
// 8: astore_2
// 9: aload_2
// 10: invokeinterface 179 1 0
// 15: ifeq +42 -> 57
// 18: aload_2
// 19: invokeinterface 183 1 0
// 24: checkcast 111 com/crumby/lib/router/FragmentLink
// 27: astore_3
// 28: aload_0
// 29: getfield 148 com/crumby/lib/widget/firstparty/omnibar/FragmentSuggestions:suggestionIds Ljava/util/Set;
// 32: aload_3
// 33: invokevirtual 186 com/crumby/lib/router/FragmentLink:getBaseUrl ()Ljava/lang/String;
// 36: invokeinterface 152 2 0
// 41: ifne -32 -> 9
// 44: aload_0
// 45: aload_3
// 46: aconst_null
// 47: invokespecial 116 com/crumby/lib/widget/firstparty/omnibar/FragmentSuggestions:addSuggestion (Lcom/crumby/lib/router/FragmentLink;Landroid/graphics/drawable/Drawable;)Lcom/crumby/lib/widget/firstparty/omnibar/FragmentSuggestion;
// 50: astore 4
// 52: aload 4
// 54: ifnonnull +6 -> 60
// 57: aload_0
// 58: monitorexit
// 59: return
// 60: aload 4
// 62: aload_1
// 63: invokevirtual 189 com/crumby/lib/widget/firstparty/omnibar/FragmentSuggestion:highlight (Ljava/lang/String;)V
// 66: aload_0
// 67: getfield 148 com/crumby/lib/widget/firstparty/omnibar/FragmentSuggestions:suggestionIds Ljava/util/Set;
// 70: aload_3
// 71: invokevirtual 186 com/crumby/lib/router/FragmentLink:getBaseUrl ()Ljava/lang/String;
// 74: invokeinterface 192 2 0
// 79: pop
// 80: goto -71 -> 9
// 83: astore_1
// 84: aload_0
// 85: monitorexit
// 86: aload_1
// 87: athrow
// Local variable table:
// start length slot name signature
// 0 88 0 this FragmentSuggestions
// 0 88 1 paramString String
// 0 88 2 paramList java.util.List<FragmentLink>
// 27 44 3 localFragmentLink FragmentLink
// 50 11 4 localFragmentSuggestion FragmentSuggestion
// Exception table:
// from to target type
// 2 9 83 finally
// 9 52 83 finally
// 60 80 83 finally
}
public void appendTryParse(String paramString)
{
if ((this.suggestionIds.isEmpty()) && (!this.searchGalleries)) {
addSuggestionWithNoBaseUrl("Try to parse \"" + paramString + "\"?", paramString, getResources().getDrawable(2130837645));
}
}
public boolean canSearchGalleries()
{
return this.searchGalleries;
}
public int getVisible()
{
return this.visible;
}
public void hide()
{
setVisibility(8);
}
public void onClick(View paramView)
{
paramView = (FragmentSuggestion)paramView.getParent();
if (!paramView.isClickable()) {
return;
}
this.breadcrumbContainer.removeBreadcrumbs();
paramView = paramView.getUrl();
Analytics.INSTANCE.newNavigationEvent("fragment suggestion click", paramView);
BusProvider.BUS.get().post(new UrlChangeEvent(paramView));
}
protected void onFinishInflate()
{
super.onFinishInflate();
int i = getChildCount() - 1;
while (i >= 0)
{
getChildAt(i).findViewById(2131492974).setOnClickListener(this);
i -= 1;
}
this.suggestionIds = new HashSet();
}
public int remainingSpace()
{
return getChildCount() - this.visible - 2;
}
public void removeSuggestions(String paramString)
{
this.visible = 0;
int i = getChildCount() - 1;
while (i >= 0)
{
getChildAt(i).setVisibility(8);
i -= 1;
}
this.suggestionIds.clear();
addSearchSuggestion(paramString);
}
public void setBreadcrumbContainer(BreadcrumbContainer paramBreadcrumbContainer)
{
this.breadcrumbContainer = paramBreadcrumbContainer;
}
public void show()
{
setVisibility(0);
}
}
/* Location: /home/dev/Downloads/apk/dex2jar-2.0/crumby-dex2jar.jar!/com/crumby/lib/widget/firstparty/omnibar/FragmentSuggestions.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | BinSlashBash/xcrumby | src/com/crumby/lib/widget/firstparty/omnibar/FragmentSuggestions.java |
45,888 | package com.linkedin.android.feed.shared;
import android.text.util.Linkify.MatchFilter;
import java.util.regex.Pattern;
public final class LinkPatterns
{
public static final Linkify.MatchFilter URL_MATCH_FILTER = new Linkify.MatchFilter()
{
public final boolean acceptMatch(CharSequence paramAnonymousCharSequence, int paramAnonymousInt1, int paramAnonymousInt2)
{
return (paramAnonymousInt1 == 0) || (paramAnonymousCharSequence.charAt(paramAnonymousInt1 - 1) != '@');
}
};
public static final String[] URL_PREFIXES = { "http://", "https://", "rtsp://" };
public static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?((?:(?:[a-zA-Z0-9 -豈-﷏ﷰ-][a-zA-Z0-9 -豈-﷏ﷰ-\\-]{0,64}\\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|(?:link|l[abcikrstuvy])|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9 -豈-﷏ﷰ-\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?(?:\\b|$)");
}
/* Location:
* Qualified Name: com.linkedin.android.feed.shared.LinkPatterns
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | reverseengineeringer/com.linkedin.android | src/com/linkedin/android/feed/shared/LinkPatterns.java |
45,889 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socksx.v5;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class Socks5AuthRequestTest {
@Test
public void testConstructorParamsAreNotNull() {
try {
new Socks5AuthRequest(null, "");
} catch (Exception e) {
assertTrue(e instanceof NullPointerException);
}
try {
new Socks5AuthRequest("", null);
} catch (Exception e) {
assertTrue(e instanceof NullPointerException);
}
}
@Test
public void testUsernameOrPasswordIsNotAscii() {
try {
new Socks5AuthRequest("παράδειγμα.δοκιμή", "password");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
new Socks5AuthRequest("username", "παράδειγμα.δοκιμή");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testUsernameOrPasswordLengthIsLessThan255Chars() {
try {
new Socks5AuthRequest(
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword",
"password");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
new Socks5AuthRequest("password",
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
}
| bfritz/netty | codec-socks/src/test/java/io/netty/handler/codec/socksx/v5/Socks5AuthRequestTest.java |
45,890 | package org.xm.xmnlp.tokenizer;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xm.xmnlp.Xmnlp;
import org.xm.xmnlp.corpus.tag.Nature;
import org.xm.xmnlp.seg.Segment;
import org.xm.xmnlp.seg.domain.Term;
/**
* 可识别URL的分词器
* Created by xuming on 2016/7/29.
*/
public class URLTokenizer {
private static Segment SEGMENT = Xmnlp.newSegment();
private static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(((([a-zA-Z0-9][a-zA-Z0-9\\-]*)*[a-zA-Z0-9]\\.)+((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?");
public static List<Term> segment(String text) {
List<Term> termList = new LinkedList<Term>();
Matcher matcher = WEB_URL.matcher(text);
int begin = 0;
int end;
while (matcher.find()) {
end = matcher.start();
termList.addAll(SEGMENT.seg(text.substring(begin, end)));
termList.add(new Term(matcher.group(), Nature.xu));
begin = matcher.end();
}
if (begin < text.length()) termList.addAll(SEGMENT.seg(text.substring(begin)));
return termList;
}
}
| atcogit/atconlp | src/main/java/org/xm/xmnlp/tokenizer/URLTokenizer.java |
45,892 | package android.util;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Patterns {
public static final Pattern AUTOLINK_EMAIL_ADDRESS = Pattern.compile("((?:\\b|$|^)(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'\\.]{0,62}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'])?@(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63}))(?:\\b|$|^))");
public static final Pattern AUTOLINK_WEB_URL = Pattern.compile("(((?:\\b|$|^)(?:(?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))|((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^)))");
public static final Pattern AUTOLINK_WEB_URL_EMUI = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:" + DOMAIN_NAME_EMUI + ")" + "(?:\\:\\d{1,5})?)" + "((?:\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~" + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))+[\\;\\.\\=\\?\\/\\+\\)][a-zA-Z0-9\\%\\#\\&\\-\\_\\.\\~]*)" + "|(?:\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~" + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*))?" + "(?:\\b|$|(?=[ -豈-﷏ﷰ-]))", 2);
public static final Pattern DOMAIN_NAME = Pattern.compile(DOMAIN_NAME_STR);
public static final Pattern DOMAIN_NAME_EMUI = Pattern.compile("(([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}\\.)+[a-zA-Z]{2,63}|" + IP_ADDRESS + ")");
private static final String DOMAIN_NAME_STR = "(([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
public static final Pattern EMAIL_ADDRESS = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+");
private static final String EMAIL_ADDRESS_DOMAIN = "(?=.{1,255}(?:\\s|$|^))([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String EMAIL_ADDRESS_LOCAL_PART = "[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'\\.]{0,62}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'])?";
private static final String EMAIL_CHAR = "a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]\\+\\-_%'";
private static final String GOOD_GTLD_CHAR_EMUI = "a-zA-Z";
@Deprecated
public static final String GOOD_IRI_CHAR = "a-zA-Z0-9 -豈-﷏ﷰ-";
public static final String GOOD_IRI_CHAR_EMUI = "a-zA-Z0-9";
private static final String GTLD_EMUI = "[a-zA-Z]{2,63}";
private static final String HOST_NAME = "([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String HOST_NAME_EMUI = "([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}\\.)+[a-zA-Z]{2,63}";
static final String IANA_TOP_LEVEL_DOMAINS = "(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))";
public static final Pattern IP_ADDRESS = Pattern.compile(IP_ADDRESS_STRING);
private static final String IP_ADDRESS_STRING = "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))";
private static final String IRI_EMUI = "[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]){0,1}";
private static final String IRI_LABEL = "[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}";
private static final String LABEL_CHAR = "a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
private static final String PATH_AND_QUERY = "[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*";
public static final Pattern PHONE = Pattern.compile("(\\+[0-9]+[\\- \\.]*)?(\\([0-9]+\\)[\\- \\.]*)?([0-9][0-9\\- \\.]+[0-9])");
private static final String PORT_NUMBER = "\\:\\d{1,5}";
private static final String PROTOCOL = "(?i:http|https|rtsp)://";
private static final String PUNYCODE_TLD = "xn\\-\\-[\\w\\-]{0,58}\\w";
private static final String RELAXED_DOMAIN_NAME = "(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
private static final String STRICT_DOMAIN_NAME = "(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))";
private static final String STRICT_HOST_NAME = "(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))";
private static final String STRICT_TLD = "(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w)";
private static final String TLD = "(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})";
private static final String TLD_CHAR = "a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
@Deprecated
public static final Pattern TOP_LEVEL_DOMAIN = Pattern.compile(TOP_LEVEL_DOMAIN_STR);
@Deprecated
public static final String TOP_LEVEL_DOMAIN_STR = "((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw])";
@Deprecated
public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL = "(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))";
private static final String UCS_CHAR = "[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]";
private static final String USER_INFO = "(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@";
public static final Pattern WEB_URL = Pattern.compile("(((?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(([a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(xn\\-\\-[\\w\\-]{0,58}\\w|[a-zA-Z[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]{2,63})|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)([/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))");
private static final String WEB_URL_WITHOUT_PROTOCOL = "((?:\\b|$|^)(?<!:\\/\\/)((?:(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}\\.)+(?:(?:(?:aaa|aarp|abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|afl|agency|aig|airforce|airtel|allfinanz|alsace|amica|amsterdam|android|apartments|app|apple|aquarelle|aramco|archi|army|arpa|arte|asia|associates|attorney|auction|audio|auto|autos|axa|azure|a[cdefgilmoqrstuwxz])|(?:band|bank|bar|barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beats|beer|bentley|berlin|best|bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bms|bmw|bnl|bnpparibas|boats|bom|bond|boo|boots|boutique|bradesco|bridgestone|broadway|broker|brother|brussels|budapest|build|builders|business|buzz|bzh|b[abdefghijmnorstvwyz])|(?:cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|car|caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cipriani|cisco|citic|city|cityeats|claims|cleaning|click|clinic|clothing|cloud|club|clubmed|coach|codes|coffee|college|cologne|com|commbank|community|company|computer|comsec|condos|construction|consulting|contractors|cooking|cool|coop|corsica|country|coupons|courses|credit|creditcard|creditunion|cricket|crown|crs|cruises|csc|cuisinella|cymru|cyou|c[acdfghiklmnoruvwxyz])|(?:dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|dell|delta|democrat|dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|doha|domains|doosan|download|drive|durban|dvag|d[ejkmoz])|(?:earth|eat|edu|education|email|emerck|energy|engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|exchange|expert|exposed|express|e[cegrstu])|(?:fage|fail|fairwinds|faith|family|fan|fans|farm|fashion|feedback|ferrero|film|final|finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|f[ijkmor])|(?:gal|gallery|game|garden|gbiz|gdn|gea|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|gold|goldpoint|golf|goo|goog|google|gop|gov|grainger|graphics|gratis|green|gripe|group|gucci|guge|guide|guitars|guru|g[abdefghilmnpqrstuwy])|(?:hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|hyundai|h[kmnrtu])|(?:ibm|icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|international|investments|ipiranga|irish|ist|istanbul|itau|iwc|i[delmnoqrst])|(?:jaguar|java|jcb|jetzt|jewelry|jlc|jll|jobs|joburg|jprs|juegos|j[emop])|(?:kaufen|kddi|kia|kim|kinder|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|k[eghimnprwyz])|(?:lacaixa|lancaster|land|landrover|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|life|lifestyle|lighting|limited|limo|linde|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltd|ltda|lupin|luxe|luxury|l[abcikrstuvy])|(?:madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|meet|melbourne|meme|memorial|men|menu|meo|miami|microsoft|mil|mini|mma|mobi|moda|moe|moi|mom|monash|money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|mtr|museum|mutuelle|m[acdeghklmnopqrstuvwxyz])|(?:nadex|nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|nra|nrw|ntt|nyc|n[acefgilopruz])|(?:obi|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|otsuka|ovh|om)|(?:page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|photos|physio|piaget|pics|pictet|pictures|ping|pink|pizza|place|play|playstation|plumbing|plus|pohl|poker|porn|post|praxi|press|pro|prod|productions|prof|properties|property|protection|pub|p[aefghklmnrstwy])|(?:qpon|quebec|qa)|(?:racing|realtor|realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocher|rocks|rodeo|rsvp|ruhr|run|rwe|ryukyu|r[eosuw])|(?:saarland|sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sapo|sarl|saxo|sbs|sca|scb|schmidt|scholarships|school|schule|schwarz|science|scor|scot|seat|security|seek|sener|services|seven|sew|sex|sexy|shiksha|shoes|show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|soy|space|spiegel|spreadbetting|srl|stada|starhub|statoil|stc|stcgroup|stockholm|studio|study|style|sucks|supplies|supply|support|surf|surgery|suzuki|swatch|swiss|sydney|systems|s[abcdeghijklmnortuvxyz])|(?:tab|taipei|tatamotors|tatar|tattoo|tax|taxi|team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|theatre|tickets|tienda|tips|tires|tirol|today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|tui|t[cdfghjklmnortvwz])|(?:ubs|university|uno|uol|u[agksyz])|(?:vacations|vana|vegas|ventures|versicherung|vet|viajes|video|villas|vin|virgin|vision|vista|vistaprint|viva|vlaanderen|vodka|vote|voting|voto|voyage|v[aceginu])|(?:wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|w[fs])|(?:ελ|бел|дети|ком|мкд|мон|москва|онлайн|орг|рус|рф|сайт|срб|укр|қаз|հայ|קום|ارامكو|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بازار|بھارت|تونس|سودان|سورية|شبكة|عراق|عمان|فلسطين|قطر|كوم|مصر|مليسيا|موقع|कॉम|नेट|भारत|संगठन|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|భారత్|ලංකා|คอม|ไทย|გე|みんな|グーグル|コム|世界|中信|中国|中國|中文网|企业|佛山|信息|健康|八卦|公司|公益|台湾|台灣|商城|商店|商标|在线|大拿|娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新加坡|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|香港|닷넷|닷컴|삼성|한국|xbox|xerox|xin|xn\\-\\-11b4c3d|xn\\-\\-1qqw23a|xn\\-\\-30rr7y|xn\\-\\-3bst00m|xn\\-\\-3ds443g|xn\\-\\-3e0b707e|xn\\-\\-3pxu8k|xn\\-\\-42c2d9a|xn\\-\\-45brj9c|xn\\-\\-45q11c|xn\\-\\-4gbrim|xn\\-\\-55qw42g|xn\\-\\-55qx5d|xn\\-\\-6frz82g|xn\\-\\-6qq986b3xl|xn\\-\\-80adxhks|xn\\-\\-80ao21a|xn\\-\\-80asehdb|xn\\-\\-80aswg|xn\\-\\-90a3ac|xn\\-\\-90ais|xn\\-\\-9dbq2a|xn\\-\\-9et52u|xn\\-\\-b4w605ferd|xn\\-\\-c1avg|xn\\-\\-c2br7g|xn\\-\\-cg4bki|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-czr694b|xn\\-\\-czrs0t|xn\\-\\-czru2d|xn\\-\\-d1acj3b|xn\\-\\-d1alf|xn\\-\\-efvy88h|xn\\-\\-estv75g|xn\\-\\-fhbei|xn\\-\\-fiq228c5hs|xn\\-\\-fiq64b|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fjq720a|xn\\-\\-flw351e|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hxt814e|xn\\-\\-i1b6b1a6a2e|xn\\-\\-imr513n|xn\\-\\-io0a7i|xn\\-\\-j1aef|xn\\-\\-j1amh|xn\\-\\-j6w193g|xn\\-\\-kcrx77d1x4a|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-kput3i|xn\\-\\-l1acc|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgb9awbf|xn\\-\\-mgba3a3ejt|xn\\-\\-mgba3a4f16a|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbab2bd|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-mgbpl2fh|xn\\-\\-mgbtx2b|xn\\-\\-mgbx4cd0ab|xn\\-\\-mk1bu44c|xn\\-\\-mxtq1m|xn\\-\\-ngbc5azd|xn\\-\\-node|xn\\-\\-nqv7f|xn\\-\\-nqv7fs00ema|xn\\-\\-nyqy26a|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1acf|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-pssy2u|xn\\-\\-q9jyb4c|xn\\-\\-qcka1pmc|xn\\-\\-qxam|xn\\-\\-rhqv96g|xn\\-\\-s9brj9c|xn\\-\\-ses554g|xn\\-\\-t60b56a|xn\\-\\-tckwe|xn\\-\\-unup4y|xn\\-\\-vermgensberater\\-ctb|xn\\-\\-vermgensberatung\\-pwb|xn\\-\\-vhquv|xn\\-\\-vuq861b|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xhq521b|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-y9a3aq|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zfr164b|xperia|xxx|xyz)|(?:yachts|yamaxun|yandex|yodobashi|yoga|yokohama|youtube|y[et])|(?:zara|zip|zone|zuerich|z[amw]))|xn\\-\\-[\\w\\-]{0,58}\\w))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))";
private static final String WEB_URL_WITH_PROTOCOL = "((?:\\b|$|^)(?:(?:(?i:http|https|rtsp)://(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)(?:(?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]](?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]_\\-]{0,61}[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]]]){0,1}(?:\\.(?=\\S))?)+|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))?(?:\\:\\d{1,5})?)(?:[/\\?](?:(?:[a-zA-Z0-9[ -豈-﷏ﷰ-𐀀-𠀀-𰀀------------&&[^ [ - ]
]];/\\?:@&=#~\\-\\.\\+!\\*'\\(\\),_\\$])|(?:%[a-fA-F0-9]{2}))*)?(?:\\b|$|^))";
private static final String WORD_BOUNDARY = "(?:\\b|$|^)";
public static final String concatGroups(Matcher matcher) {
StringBuilder b = new StringBuilder();
int numGroups = matcher.groupCount();
for (int i = 1; i <= numGroups; i++) {
String s = matcher.group(i);
if (s != null) {
b.append(s);
}
}
return b.toString();
}
public static final String digitsAndPlusOnly(Matcher matcher) {
StringBuilder buffer = new StringBuilder();
String matchingRegion = matcher.group();
int size = matchingRegion.length();
for (int i = 0; i < size; i++) {
char character = matchingRegion.charAt(i);
if (character == '+' || Character.isDigit(character)) {
buffer.append(character);
}
}
return buffer.toString();
}
private Patterns() {
}
public static Pattern getWebUrl() {
if (Locale.CHINESE.getLanguage().equals(Locale.getDefault().getLanguage())) {
return AUTOLINK_WEB_URL_EMUI;
}
return AUTOLINK_WEB_URL;
}
}
| SivanLiu/HwFrameWorkSource | Mate10_8_1_0/src/main/java/android/util/Patterns.java |
45,893 | package org.openxdata.server.validation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Tests File Validations
*
* @author maimoona kausar
*
*/
public class FileValidationsTest {
@Test
public void testValidateFileName() throws Exception {
String[] fileNamesValid = new String[]{"glassfish-3.0.1","CmapToolsLogs","My_Cmaps","netbeans-6.9","2083436590_f899ee8925.jpg","art-isl abstract 00040","Generic SMS Application.gif","Nokia PC Suite 7.1.rar"
,"Permissions-2.xlsx","islandart-350w-255x230.jpg","tango-icon-theme-0.8.90","ReminderResponseRecord_2010-11-03.zip","rxtx-2.1-7-bins-r2.zip","testcaseXout.xls_0.ods"
,"java j2ee interviewgwt-ext and spring mvc_files","Java ServerPages JSP- java.itags.org_files"
,"ms5366.aspx_files","Form Validation_ GWT_ Java_files","Surprisingly_Rockin_JavaScript_DOM_Prog_GWT.pdf","Surprisingly_Rockin_JavaScript_DOM_Prog_GWT","thread.jspa.html","windows.php.html"
,"專營 以 較 便宜 的 價","錢 售 賣 日 本 品 牌 ","風格 如Rδοκι","μήπαράδειγ","μα.δοκιμή參","加大抽獎0拉視","乎參加人數抽參加"
,"人數.拉視乎參","ç²æ–éå.æ—æœ","RÎÎκιμÎÏÎÏ","ÎÎειγμÎ.Î","ÎκιμPelÃ","sendåŽsampl","eviåçŸ ˆä "
,"較 ä¾åœ çš","åƒ¹éŒ å è³","æ— æœ å çŒ","çŽ 0æè– ä¹Žåƒ","åŠäººæ抽åˆçŸ"
,"ä 較 ä¾åœ","çšåƒ¹éŒ åè³æ— æœ","å çŒ éæ ¼ ååƒ","åŠ å 抽 çŽ","0æè– ä¹Žåƒ","åŠäººæ 抽","åƒåŠ å抽çŽ0"
,"æè–乎åƒåŠ","人æ抽"};
String[] fileNamesInvalid = new String[]{"2576_1115456049327_1314721303_30337429_6143570_n.jpg","Log4j Tutorial| How to send the log messages to a File | Veera Sundar_files"
,"ColorPicker.com : Quick Online Color Picker Tool_files","/home/maimoonak/Music/articleregx_files","JSP - JSP tutorial, example, code_files","fg \"dfkld\"cxvC","maim `k 12File","jamal ! Files","maim@kFile"
,"pol:kjFile","fk ^grad","maira<and>jam","iftik;kaus","j2e'jhj'jsp","jam\\mam","jam/maam0","sort:insert"
,"<miss m k >","whyFile?exit","now, never","Java ServerPages (JSP)- java.itags.org_files","ms536651#@!~$%^&*_-+=|:;<>,.?/VS.85).aspx_files"
,"my`file","my~332file","my!!4ttfile","myf@34file","my#file","my$file","my%`file","my^vbfile","my&file"
,"my*gjfile","mispalcedfile+found","my=file","my{own}file","my[own]file","my`file?noitsnot","sdh”ampleviå"
,"sendåŽ�cx","send去sampleviå","dsdh’sdjs","djxdj·sdjsd","sdsdjs¥zsh","sdsjd¬sdj","dsd¿aus","sdsd®sdd"
,"sdhdj€ss","sxds±dsd","sasdhs©hssns","gdshgd°shs","dshdj<fgfdg>ddff","dhjh‡sjdhjs","sahsh¢hsajhs","bkjhkjh‰sgasg","sghg¤dsdj","sdd§sdn"};
for (String string : fileNamesValid) {
assertTrue("Valid File Name : "+string+",was rejected.",FileValidations.validateOutputFilename(string));
}
for (String string : fileNamesInvalid) {
assertFalse("Invalid FileName: "+string+",was accepted.",FileValidations.validateOutputFilename(string));
}
String[] fileNamesValidnsp = new String[]{"glassfish-3.0.1","CmapToolsLogs","My_Cmaps","netbeans-6.9","2083436590_f899ee8925.jpg","art-islabstract00040","GenericSMSApplication.gif","NokiaPCSuite7.1.rar"
,"Permissions-2.xlsx","islandart-350w-255x230.jpg","tango-icon-theme-0.8.90","ReminderResponseRecord_2010-11-03.zip","rxtx-2.1-7-bins-r2.zip","testcaseXout.xls_0.ods"
,"java-j2ee-interviewgwt-ext-and-spring-mvc_files","Java-ServerPages-JSP--java.itags.org_files"
,"ms5366.aspx_files","FormValidation_GWT_Java_files","Surprisingly_Rockin_JavaScript_DOM_Prog_GWT.pdf","Surprisingly_Rockin_JavaScript_DOM_Prog_GWT","thread.jspa.html","windows.php.html"
,"專營以較便宜的價","錢售賣日本品牌","風格如Rδοκι","μήπαράδειγ","μα.δοκιμή參","加大抽獎0拉視","乎參加人數抽參加"
,"人數.拉視乎參","ç²æ–éå.æ—æœ","RÎÎκιμÎÏÎÏ","ÎÎειγμÎ.Î","ÎκιμPelÃ","sendåŽsampl","eviå矈ä"
,"較ä¾åœçš","價éŒåè³","æ—æœåçŒ","çŽ0æè乎åƒ","åŠäººæ抽åˆçŸ"
,"ä較ä¾åœ","çšåƒ¹éŒåè³æ—æœ","åçŒéæ¼ååƒ","åŠå抽çŽ","0æè–乎åƒ","åŠäººæ抽","åƒåŠå抽çŽ0"
,"æè–乎åƒåŠ","人æ抽"};
String[] fileNamesInvalidnsp = new String[]{"2576_1115456049327_1314721303_30337429_6143570_n.jpg","Log4j Tutorial| How to send the log messages to a File | Veera Sundar_files"
,"ColorPicker.com:QuickOnlinColorickerTool_files","/home/maimoonak/Music/articleregx_files","JSP-JSPtutorial,example,code_files","fg \"dfkld\"cxvC","maim `k 12File","jamal ! Files","maim@kFile"
,"pol:kjFile","fk ^grad","maira<and>jam","iftik;kaus","j2e'jhj'jsp","jam\\mam","jam/maam0","sort:insert"
,"<miss m k >","whyFile?exit","now,never","Java ServerPages (JSP)- java.itags.org_files","ms536651#@!~$%^&*_-+=|:;<>,.?/VS.85).aspx_files"
,"my`file","my~332file","my!!4ttfile","myf@34file","my#file","my$file","my%`file","my^vbfile","my&file"
,"my*gjfile","mispalcedfile+found","my=file","my{own}file","my[own]file","my`file?noitsnot","sdh”ampleviå"
,"sendåŽ�cx","send去sampleviå","dsdh’sdjs","djxdj·sdjsd","sdsdjs¥zsh","sdsjd¬sdj","dsd¿aus","sdsd®sdd"
,"sdhdj€ss","sxds±dsd","sasdhs©hssns","gdshgd°shs","dshdj<fgfdg>ddff","dhjh‡sjdhjs","sahsh¢hsajhs","bkjhkjh‰sgasg","sghg¤dsdj","sdd§sdn"};
for (String string : fileNamesValidnsp) {
assertTrue("Valid NoSpaceFile Name : "+string+",was rejected.",FileValidations.validateNoSpaceFilename(string));
}
for (String string : fileNamesInvalidnsp) {
assertFalse("Invalid NoSpaceFileFileName: "+string+",was accepted.",FileValidations.validateNoSpaceFilename(string));
}
}
}
| mortalisk/openxdata-oc | server/src/test/java/org/openxdata/server/validation/FileValidationsTest.java |
45,894 | /*
* <author>Han He</author>
* <email>[email protected]</email>
* <create-date>2018-11-10 10:51 AM</create-date>
*
* <copyright file="DemoPipeline.java">
* Copyright (c) 2018, Han He. All Rights Reserved, http://www.hankcs.com/
* See LICENSE file in the project root for full license information.
* </copyright>
*/
package com.diwayou.nlp;
import com.hankcs.hanlp.corpus.document.sentence.word.IWord;
import com.hankcs.hanlp.model.perceptron.PerceptronLexicalAnalyzer;
import com.hankcs.hanlp.tokenizer.pipe.LexicalAnalyzerPipeline;
import com.hankcs.hanlp.tokenizer.pipe.Pipe;
import com.hankcs.hanlp.tokenizer.pipe.RegexRecognizePipe;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
/**
* 演示流水线模式,几个概念:
* - pipe:流水线的一节管道,执行统计分词或规则逻辑
* - flow:管道的数据流,在同名方法中执行本节管道的业务
* - pipeline:流水线,由至少一节管道(统计分词管道)构成,可自由调整管道的拼装方式
*
* @author hankcs
*/
public class DemoPipeline {
private static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?(?:(((([a-zA-Z0-9][a-zA-Z0-9\\-]*)*[a-zA-Z0-9]\\.)+((aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(biz|b[abdefghijmnorstvwyz])|(cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(edu|e[cegrstu])|f[ijkmor]|(gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(info|int|i[delmnoqrst])|(jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(name|net|n[acefgilopruz])|(org|om)|(pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9]))))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?");
private static final Pattern EMAIL = Pattern.compile("(\\w+(?:[-+.]\\w+)*)@(\\w+(?:[-.]\\w+)*\\.\\w+(?:[-.]\\w+)*)");
public static void main(String[] args) throws IOException {
LexicalAnalyzerPipeline analyzer = new LexicalAnalyzerPipeline(new PerceptronLexicalAnalyzer());
// 管道顺序=优先级,自行调整管道顺序以控制优先级
analyzer.addFirst(new RegexRecognizePipe(WEB_URL, "【网址】"));
analyzer.addFirst(new RegexRecognizePipe(EMAIL, "【邮件】"));
analyzer.addLast(new Pipe<List<IWord>, List<IWord>>() // 自己写个管道也并非难事
{
@Override
public List<IWord> flow(List<IWord> input) {
for (IWord word : input) {
if ("nx".equals(word.getLabel()))
word.setLabel("字母");
}
return input;
}
});
String text = "HanLP的项目地址是https://github.com/hankcs/HanLP,联系邮箱[email protected]";
System.out.println(analyzer.analyze(text));
}
}
| P79N6A/acm | src/main/java/com/diwayou/nlp/DemoPipeline.java |
45,895 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedByteChannel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import sun.net.util.IPAddressUtil;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksCmdType cmdType,
SocksAddressType addressType,
String host,
int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host +
" port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
EmbeddedByteChannel embedder = new EmbeddedByteChannel(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.addressType() == SocksAddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocksRequest);
} else {
msg = (SocksCmdRequest) embedder.readInbound();
assertSame(msg.cmdType(), cmdType);
assertSame(msg.addressType(), addressType);
assertEquals(msg.host(), host);
assertEquals(msg.port(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1", };
int[] ports = {0, 32769, 65535 };
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() {
String[] hosts = {SocksCommonUtils.ipv6toStr(IPAddressUtil.textToNumericFormatV6("::1"))};
int[] ports = {0, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {0, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (SocksCmdType cmdType : SocksCmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.UNKNOWN, host, port);
}
}
}
| beykery/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,896 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socksx.v5;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class DefaultSocks5PasswordAuthRequestTest {
@Test
public void testConstructorParamsAreNotNull() {
try {
new DefaultSocks5PasswordAuthRequest(null, "");
} catch (Exception e) {
assertTrue(e instanceof NullPointerException);
}
try {
new DefaultSocks5PasswordAuthRequest("", null);
} catch (Exception e) {
assertTrue(e instanceof NullPointerException);
}
}
@Test
public void testUsernameOrPasswordIsNotAscii() {
try {
new DefaultSocks5PasswordAuthRequest("παράδειγμα.δοκιμή", "password");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
new DefaultSocks5PasswordAuthRequest("username", "παράδειγμα.δοκιμή");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testUsernameOrPasswordLengthIsLessThan255Chars() {
try {
new DefaultSocks5PasswordAuthRequest(
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword",
"password");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
new DefaultSocks5PasswordAuthRequest("password",
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
}
| casidiablo/netty | codec-socks/src/test/java/io/netty/handler/codec/socksx/v5/DefaultSocks5PasswordAuthRequestTest.java |
45,898 | package com.openwallet.core.wallet;
import com.openwallet.core.coins.BitcoinMain;
import com.openwallet.core.coins.CoinType;
import com.openwallet.core.coins.DogecoinTest;
import com.openwallet.core.coins.NuBitsMain;
import com.openwallet.core.coins.Value;
import com.openwallet.core.coins.VpncoinMain;
import com.openwallet.core.exceptions.AddressMalformedException;
import com.openwallet.core.exceptions.Bip44KeyLookAheadExceededException;
import com.openwallet.core.exceptions.KeyIsEncryptedException;
import com.openwallet.core.exceptions.MissingPrivateKeyException;
import com.openwallet.core.network.AddressStatus;
import com.openwallet.core.network.BlockHeader;
import com.openwallet.core.network.ServerClient.HistoryTx;
import com.openwallet.core.network.ServerClient.UnspentTx;
import com.openwallet.core.network.interfaces.ConnectionEventListener;
import com.openwallet.core.network.interfaces.TransactionEventListener;
import com.openwallet.core.protos.Protos;
import com.openwallet.core.wallet.families.bitcoin.BitAddress;
import com.openwallet.core.wallet.families.bitcoin.BitBlockchainConnection;
import com.openwallet.core.wallet.families.bitcoin.BitSendRequest;
import com.openwallet.core.wallet.families.bitcoin.BitTransaction;
import com.openwallet.core.wallet.families.bitcoin.BitTransactionEventListener;
import com.openwallet.core.wallet.families.bitcoin.OutPointOutput;
import com.openwallet.core.wallet.families.bitcoin.TrimmedOutPoint;
import com.google.common.collect.ImmutableList;
import org.bitcoinj.core.ChildMessage;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence.Source;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.core.Utils;
import org.bitcoinj.crypto.DeterministicHierarchy;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.crypto.KeyCrypter;
import org.bitcoinj.crypto.KeyCrypterScrypt;
import org.bitcoinj.store.UnreadableWalletException;
import org.bitcoinj.utils.BriefLogFormatter;
import org.bitcoinj.wallet.DeterministicSeed;
import org.bitcoinj.wallet.KeyChain;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.spongycastle.crypto.params.KeyParameter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.openwallet.core.Preconditions.checkNotNull;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author John L. Jegutanis
*/
public class WalletPocketHDTest {
static final CoinType BTC = BitcoinMain.get();
static final CoinType DOGE = DogecoinTest.get();
static final CoinType NBT = NuBitsMain.get();
static final CoinType VPN = VpncoinMain.get();
static final List<String> MNEMONIC = ImmutableList.of("citizen", "fever", "scale", "nurse", "brief", "round", "ski", "fiction", "car", "fitness", "pluck", "act");
static final byte[] AES_KEY_BYTES = {0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7};
static final long AMOUNT_TO_SEND = 2700000000L;
static final String MESSAGE = "test";
static final String MESSAGE_UNICODE = "δοκιμή испытание 测试";
static final String EXPECTED_BITCOIN_SIG = "IMBbIFDDuUwomYlvSjwWytqP/CXYym2yOKbJUx8Y+ujzZKBwoCFMr73GUxpr1Ird/DvnNZcsQLphvx18ftqN54o=";
static final String EXPECTED_BITCOIN_SIG_UNICODE = "IGGZEOBsVny5dozTOfc2/3UuvmZGdDI4XK/03HIk34PILd2oXbnq+87GINT3lumeXcgSO2NkGzUFcQ1SCSVI3Hk=";
static final String EXPECTED_NUBITS_SIG = "IMuzNZTZIjZjLicyDFGzqFl21vqNBGW1N5m4qHBRqbTvLBbkQeGjraeLmZEt7mRH4MSMPLFXW2T3Maz+HYx1tEc=";
static final String EXPECTED_NUBITS_SIG_UNICODE = "Hx7xkBbboXrp96dbQrJFzm2unTGwLstjbWlKa1/N1E4LJqbwJAJR1qIvwXm6LHQFnLOzwoQA45zYNjwUEPMc8sg=";
DeterministicSeed seed = new DeterministicSeed(MNEMONIC, null, "", 0);
DeterministicKey masterKey = HDKeyDerivation.createMasterPrivateKey(checkNotNull(seed.getSeedBytes()));
DeterministicHierarchy hierarchy = new DeterministicHierarchy(masterKey);
DeterministicKey rootKey = hierarchy.get(DOGE.getBip44Path(0), false, true);
KeyParameter aesKey = new KeyParameter(AES_KEY_BYTES);
KeyCrypter crypter = new KeyCrypterScrypt();
WalletPocketHD pocket;
@Before
public void setup() {
BriefLogFormatter.init();
pocket = new WalletPocketHD(rootKey, DOGE, null, null);
pocket.keys.setLookaheadSize(20);
}
@Test
public void testId() throws Exception {
assertEquals("8747886e9a77fe2a1588df3168b867648434d6d339b0b448793ae1db8f283f41", pocket.getId());
}
@Test
public void testSingleAddressWallet() throws Exception {
ECKey key = pocket.keys.getCurrentUnusedKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
BitWalletSingleKey bitWalletSingleKey = new BitWalletSingleKey(DOGE, key);
bitWalletSingleKey.onConnection(getBlockchainConnection(DOGE));
assertEquals(DOGE.value("10"), bitWalletSingleKey.getBalance());
}
@Test
public void xpubWallet() {
String xpub = "xpub67tVq9TLPPoaHVSiYu8mqahm3eztTPUts6JUftNq3pZF1PJwjknrTqQhjc2qRGd6vS8wANu7mLnqkiUzFZ1xZsAZoUMi8o6icMhzGCAhcSW";
DeterministicKey key = DeterministicKey.deserializeB58(null, xpub);
WalletPocketHD account = new WalletPocketHD(key, BTC, null, null);
assertEquals("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", account.getReceiveAddress().toString());
account = new WalletPocketHD(key, NBT, null, null);
assertEquals("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", account.getReceiveAddress().toString());
}
@Test
public void xpubWalletSerialized() throws Exception {
WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null);
Protos.WalletPocket proto = account.toProtobuf();
WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null);
assertEquals(account.getPublicKeySerialized(), newAccount.getPublicKeySerialized());
}
@Test
public void signMessage() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException {
WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature());
signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature());
pocketHD = new WalletPocketHD(rootKey, NBT, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_NUBITS_SIG, signedMessage.getSignature());
signedMessage = new SignedMessage("BNvJUwg3BgkbQk5br1CxvHxdcDp1EC3saE", MESSAGE_UNICODE);
pocketHD.signMessage(signedMessage, null);
assertEquals(EXPECTED_NUBITS_SIG_UNICODE, signedMessage.getSignature());
}
@Test
public void signMessageEncrypted() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException {
WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
pocketHD.encrypt(crypter, aesKey);
SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE);
pocketHD.signMessage(signedMessage, aesKey);
assertEquals(EXPECTED_BITCOIN_SIG, signedMessage.getSignature());
signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE_UNICODE);
pocketHD.signMessage(signedMessage, aesKey);
assertEquals(EXPECTED_BITCOIN_SIG_UNICODE, signedMessage.getSignature());
}
@Test
public void signMessageEncryptedFailed() throws AddressMalformedException, MissingPrivateKeyException, KeyIsEncryptedException {
WalletPocketHD pocketHD = new WalletPocketHD(rootKey, BTC, null, null);
pocketHD.getReceiveAddress(); // Generate the first key
pocketHD.encrypt(crypter, aesKey);
SignedMessage signedMessage = new SignedMessage("1KUDsEDqSBAgxubSEWszoA9xscNRRCmujM", MESSAGE);
pocketHD.signMessage(signedMessage, null);
assertEquals(SignedMessage.Status.KeyIsEncrypted, signedMessage.status);
}
@Test
public void watchingAddresses() {
List<AbstractAddress> watchingAddresses = pocket.getAddressesToWatch();
assertEquals(40, watchingAddresses.size()); // 20 + 20 lookahead size
for (int i = 0; i < addresses.size(); i++) {
assertEquals(addresses.get(i), watchingAddresses.get(i).toString());
}
}
@Test
public void issuedKeys() throws Bip44KeyLookAheadExceededException {
List<BitAddress> issuedAddresses = new ArrayList<>();
assertEquals(0, pocket.getIssuedReceiveAddresses().size());
assertEquals(0, pocket.keys.getNumIssuedExternalKeys());
issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
BitAddress freshAddress = pocket.getFreshReceiveAddress();
assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
assertEquals(1, pocket.getIssuedReceiveAddresses().size());
assertEquals(1, pocket.keys.getNumIssuedExternalKeys());
assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses());
issuedAddresses.add(0, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
freshAddress = pocket.getFreshReceiveAddress();
assertEquals(freshAddress, pocket.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS));
assertEquals(2, pocket.getIssuedReceiveAddresses().size());
assertEquals(2, pocket.keys.getNumIssuedExternalKeys());
assertEquals(issuedAddresses, pocket.getIssuedReceiveAddresses());
}
@Test
public void issuedKeysLimit() throws Exception {
assertTrue(pocket.canCreateFreshReceiveAddress());
try {
for (int i = 0; i < 100; i++) {
pocket.getFreshReceiveAddress();
}
} catch (Bip44KeyLookAheadExceededException e) {
assertFalse(pocket.canCreateFreshReceiveAddress());
// We haven't used any key so the total must be 20 - 1 (the unused key)
assertEquals(19, pocket.getNumberIssuedReceiveAddresses());
assertEquals(19, pocket.getIssuedReceiveAddresses().size());
}
pocket.onConnection(getBlockchainConnection(DOGE));
assertTrue(pocket.canCreateFreshReceiveAddress());
try {
for (int i = 0; i < 100; i++) {
pocket.getFreshReceiveAddress();
}
} catch (Bip44KeyLookAheadExceededException e) {
// try {
// pocket.getFreshReceiveAddress();
// } catch (Bip44KeyLookAheadExceededException e1) { /* ignore */ }
assertFalse(pocket.canCreateFreshReceiveAddress());
// We used 18, so the total must be (20-1)+18=37
assertEquals(37, pocket.getNumberIssuedReceiveAddresses());
assertEquals(37, pocket.getIssuedReceiveAddresses().size());
}
}
@Test
public void issuedKeysLimit2() throws Exception {
assertTrue(pocket.canCreateFreshReceiveAddress());
try {
for (int i = 0; i < 100; i++) {
pocket.getFreshReceiveAddress();
}
} catch (Bip44KeyLookAheadExceededException e) {
assertFalse(pocket.canCreateFreshReceiveAddress());
// We haven't used any key so the total must be 20 - 1 (the unused key)
assertEquals(19, pocket.getNumberIssuedReceiveAddresses());
assertEquals(19, pocket.getIssuedReceiveAddresses().size());
}
}
@Test
public void usedAddresses() throws Exception {
assertEquals(0, pocket.getUsedAddresses().size());
pocket.onConnection(getBlockchainConnection(DOGE));
// Receive and change addresses
assertEquals(13, pocket.getUsedAddresses().size());
}
private Sha256Hash send(Value value, WalletPocketHD w1, WalletPocketHD w2) throws Exception {
assertEquals(w1.getCoinType(), w2.getCoinType());
CoinType type = w1.getCoinType();
BitSendRequest req = w1.sendCoinsOffline(w2.getReceiveAddress(), value);
req.feePerTxSize = type.value("0.01");
w1.completeAndSignTx(req);
byte[] txBytes = req.tx.bitcoinSerialize();
w1.addNewTransactionIfNeeded(new BitTransaction(type, txBytes));
w2.addNewTransactionIfNeeded(new BitTransaction(type, txBytes));
return req.tx.getHash();
}
@Test
public void testSendingAndBalances() throws Exception {
DeterministicHierarchy h = new DeterministicHierarchy(masterKey);
WalletPocketHD account1 = new WalletPocketHD(h.get(BTC.getBip44Path(0), false, true), BTC, null, null);
WalletPocketHD account2 = new WalletPocketHD(h.get(BTC.getBip44Path(1), false, true), BTC, null, null);
WalletPocketHD account3 = new WalletPocketHD(h.get(BTC.getBip44Path(2), false, true), BTC, null, null);
Transaction tx = new Transaction(BTC);
tx.addOutput(BTC.oneCoin().toCoin(), account1.getReceiveAddress());
tx.getConfidence().setSource(Source.SELF);
account1.addNewTransactionIfNeeded(tx);
assertEquals(BTC.value("1"), account1.getBalance());
assertEquals(BTC.value("0"), account2.getBalance());
assertEquals(BTC.value("0"), account3.getBalance());
Sha256Hash txId = send(BTC.value("0.05"), account1, account2);
assertEquals(BTC.value("0.94"), account1.getBalance());
assertEquals(BTC.value("0"), account2.getBalance());
assertEquals(BTC.value("0"), account3.getBalance());
setTrustedTransaction(account1, txId);
setTrustedTransaction(account2, txId);
assertEquals(BTC.value("0.94"), account1.getBalance());
assertEquals(BTC.value("0.05"), account2.getBalance());
txId = send(BTC.value("0.07"), account1, account3);
setTrustedTransaction(account1, txId);
setTrustedTransaction(account3, txId);
assertEquals(BTC.value("0.86"), account1.getBalance());
assertEquals(BTC.value("0.05"), account2.getBalance());
assertEquals(BTC.value("0.07"), account3.getBalance());
txId = send(BTC.value("0.03"), account2, account3);
setTrustedTransaction(account2, txId);
setTrustedTransaction(account3, txId);
assertEquals(BTC.value("0.86"), account1.getBalance());
assertEquals(BTC.value("0.01"), account2.getBalance());
assertEquals(BTC.value("0.1"), account3.getBalance());
}
private void setTrustedTransaction(WalletPocketHD account, Sha256Hash txId) {
BitTransaction tx = checkNotNull(account.getTransaction(txId));
tx.setSource(Source.SELF);
}
@Test
public void testLoading() throws Exception {
assertFalse(pocket.isLoading());
pocket.onConnection(getBlockchainConnection(DOGE));
// TODO add fine grained control to the blockchain connection in order to test the loading status
assertFalse(pocket.isLoading());
}
@Test
public void fillTransactions() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
checkUnspentOutputs(getDummyUtxoSet(), pocket);
assertEquals(11000000000L, pocket.getBalance().value);
// Issued keys
assertEquals(18, pocket.keys.getNumIssuedExternalKeys());
assertEquals(9, pocket.keys.getNumIssuedInternalKeys());
// No addresses left to subscribe
List<AbstractAddress> addressesToWatch = pocket.getAddressesToWatch();
assertEquals(0, addressesToWatch.size());
// 18 external issued + 20 lookahead + 9 external issued + 20 lookahead
assertEquals(67, pocket.addressesStatus.size());
assertEquals(67, pocket.addressesSubscribed.size());
BitAddress receiveAddr = pocket.getReceiveAddress();
// This key is not issued
assertEquals(18, pocket.keys.getNumIssuedExternalKeys());
assertEquals(67, pocket.addressesStatus.size());
assertEquals(67, pocket.addressesSubscribed.size());
DeterministicKey key = pocket.keys.findKeyFromPubHash(receiveAddr.getHash160());
assertNotNull(key);
// 18 here is the key index, not issued keys count
assertEquals(18, key.getChildNumber().num());
assertEquals(11000000000L, pocket.getBalance().value);
}
@Test
public void serializeTransactionsBtc() throws Exception, Bip44KeyLookAheadExceededException {
WalletPocketHD account = new WalletPocketHD(rootKey, BTC, null, null);
Transaction tx = new Transaction(BTC);
tx.addOutput(BTC.oneCoin().toCoin(), account.getReceiveAddress());
account.addNewTransactionIfNeeded(tx);
testWalletSerializationForCoin(account);
}
@Test
public void serializeTransactionsNbt() throws Exception, Bip44KeyLookAheadExceededException {
WalletPocketHD account = new WalletPocketHD(rootKey, NBT, null, null);
Transaction tx = new Transaction(NBT);
tx.addOutput(NBT.oneCoin().toCoin(), account.getReceiveAddress());
account.addNewTransactionIfNeeded(tx);
testWalletSerializationForCoin(account);
}
@Test
public void serializeTransactionsVpn() throws Exception, Bip44KeyLookAheadExceededException {
WalletPocketHD account = new WalletPocketHD(rootKey, VPN, null, null);
// Test tx with null extra bytes
Transaction tx = new Transaction(VPN);
tx.setTime(0x99999999);
tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress());
account.addNewTransactionIfNeeded(tx);
WalletPocketHD newAccount = testWalletSerializationForCoin(account);
Transaction newTx = newAccount.getRawTransaction(tx.getHash());
assertNotNull(newTx);
assertNotNull(newTx.getExtraBytes());
assertEquals(0, newTx.getExtraBytes().length);
// Test tx with empty extra bytes
tx = new Transaction(VPN);
tx.setTime(0x99999999);
tx.setExtraBytes(new byte[0]);
tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress());
account.addNewTransactionIfNeeded(tx);
newAccount = testWalletSerializationForCoin(account);
newTx = newAccount.getRawTransaction(tx.getHash());
assertNotNull(newTx);
assertNotNull(newTx.getExtraBytes());
assertEquals(0, newTx.getExtraBytes().length);
// Test tx with extra bytes
tx = new Transaction(VPN);
tx.setTime(0x99999999);
byte[] bytes = {0x1, 0x2, 0x3};
tx.setExtraBytes(bytes);
tx.addOutput(VPN.oneCoin().toCoin(), account.getFreshReceiveAddress());
account.addNewTransactionIfNeeded(tx);
newAccount = testWalletSerializationForCoin(account);
newTx = newAccount.getRawTransaction(tx.getHash());
assertNotNull(newTx);
assertArrayEquals(bytes, newTx.getExtraBytes());
}
private WalletPocketHD testWalletSerializationForCoin(WalletPocketHD account) throws UnreadableWalletException {
Protos.WalletPocket proto = account.toProtobuf();
WalletPocketHD newAccount = new WalletPocketProtobufSerializer().readWallet(proto, null);
assertEquals(account.getBalance().value, newAccount.getBalance().value);
Map<Sha256Hash, BitTransaction> transactions = account.getTransactions();
Map<Sha256Hash, BitTransaction> newTransactions = newAccount.getTransactions();
for (Sha256Hash txId : transactions.keySet()) {
assertTrue(newTransactions.containsKey(txId));
assertEquals(transactions.get(txId), newTransactions.get(txId));
}
return newAccount;
}
@Test
public void serializeUnencryptedNormal() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
Protos.WalletPocket walletPocketProto = pocket.toProtobuf();
System.out.println(walletPocketProto.toString());
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null);
assertEquals(pocket.getBalance().value, newPocket.getBalance().value);
assertEquals(DOGE.value(11000000000l), newPocket.getBalance());
Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet();
checkUnspentOutputs(expectedUtxoSet, pocket);
checkUnspentOutputs(expectedUtxoSet, newPocket);
assertEquals(pocket.getCoinType(), newPocket.getCoinType());
assertEquals(pocket.getDescriptionOrCoinName(), newPocket.getDescriptionOrCoinName());
assertEquals(pocket.keys.toProtobuf().toString(), newPocket.keys.toProtobuf().toString());
assertEquals(pocket.getLastBlockSeenHash(), newPocket.getLastBlockSeenHash());
assertEquals(pocket.getLastBlockSeenHeight(), newPocket.getLastBlockSeenHeight());
assertEquals(pocket.getLastBlockSeenTimeSecs(), newPocket.getLastBlockSeenTimeSecs());
for (BitTransaction tx : pocket.getTransactions().values()) {
assertEquals(tx, newPocket.getTransaction(tx.getHash()));
BitTransaction txNew = checkNotNull(newPocket.getTransaction(tx.getHash()));
assertInputsEquals(tx.getInputs(), txNew.getInputs());
assertOutputsEquals(tx.getOutputs(false), txNew.getOutputs(false));
}
for (AddressStatus status : pocket.getAllAddressStatus()) {
if (status.getStatus() == null) continue;
assertEquals(status, newPocket.getAddressStatus(status.getAddress()));
}
// Issued keys
assertEquals(18, newPocket.keys.getNumIssuedExternalKeys());
assertEquals(9, newPocket.keys.getNumIssuedInternalKeys());
newPocket.onConnection(getBlockchainConnection(DOGE));
// No addresses left to subscribe
List<AbstractAddress> addressesToWatch = newPocket.getAddressesToWatch();
assertEquals(0, addressesToWatch.size());
// 18 external issued + 20 lookahead + 9 external issued + 20 lookahead
assertEquals(67, newPocket.addressesStatus.size());
assertEquals(67, newPocket.addressesSubscribed.size());
}
private void assertInputsEquals(List<TransactionInput> expected, List<TransactionInput> actual) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize());
}
}
private void assertOutputsEquals(List<TransactionOutput> expected, List<TransactionOutput> actual) {
assertEquals(expected.size(), actual.size());
for (int i = 0; i < expected.size(); i++) {
assertArrayEquals(expected.get(i).bitcoinSerialize(), actual.get(i).bitcoinSerialize());
}
}
@Test
public void serializeUnencryptedEmpty() throws Exception {
pocket.maybeInitializeAllKeys();
Protos.WalletPocket walletPocketProto = pocket.toProtobuf();
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, null);
assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString());
// Issued keys
assertEquals(0, newPocket.keys.getNumIssuedExternalKeys());
assertEquals(0, newPocket.keys.getNumIssuedInternalKeys());
// 20 lookahead + 20 lookahead
assertEquals(40, newPocket.keys.getActiveKeys().size());
}
@Test
public void serializeEncryptedEmpty() throws Exception {
pocket.maybeInitializeAllKeys();
pocket.encrypt(crypter, aesKey);
Protos.WalletPocket walletPocketProto = pocket.toProtobuf();
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(walletPocketProto, crypter);
assertEquals(walletPocketProto.toString(), newPocket.toProtobuf().toString());
pocket.decrypt(aesKey);
// One is encrypted, so they should not match
assertNotEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString());
newPocket.decrypt(aesKey);
assertEquals(pocket.toProtobuf().toString(), newPocket.toProtobuf().toString());
}
@Test
public void serializeEncryptedNormal() throws Exception {
pocket.maybeInitializeAllKeys();
pocket.encrypt(crypter, aesKey);
pocket.onConnection(getBlockchainConnection(DOGE));
assertEquals(DOGE.value(11000000000l), pocket.getBalance());
assertAllKeysEncrypted(pocket);
WalletPocketHD newPocket = new WalletPocketProtobufSerializer().readWallet(pocket.toProtobuf(), crypter);
assertEquals(DOGE.value(11000000000l), newPocket.getBalance());
Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet = getDummyUtxoSet();
checkUnspentOutputs(expectedUtxoSet, pocket);
checkUnspentOutputs(expectedUtxoSet, newPocket);
assertAllKeysEncrypted(newPocket);
pocket.decrypt(aesKey);
newPocket.decrypt(aesKey);
assertAllKeysDecrypted(pocket);
assertAllKeysDecrypted(newPocket);
}
private void checkUnspentOutputs(Map<TrimmedOutPoint, OutPointOutput> expectedUtxoSet, WalletPocketHD pocket) {
Map<TrimmedOutPoint, OutPointOutput> pocketUtxoSet = pocket.getUnspentOutputs(false);
for (OutPointOutput utxo : expectedUtxoSet.values()) {
assertEquals(utxo, pocketUtxoSet.get(utxo.getOutPoint()));
}
}
private void assertAllKeysDecrypted(WalletPocketHD pocket) {
List<ECKey> keys = pocket.keys.getKeys(false);
for (ECKey k : keys) {
DeterministicKey key = (DeterministicKey) k;
assertFalse(key.isEncrypted());
}
}
private void assertAllKeysEncrypted(WalletPocketHD pocket) {
List<ECKey> keys = pocket.keys.getKeys(false);
for (ECKey k : keys) {
DeterministicKey key = (DeterministicKey) k;
assertTrue(key.isEncrypted());
}
}
@Test
public void createDustTransactionFee() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp");
Value softDust = DOGE.getSoftDustLimit();
assertNotNull(softDust);
// Send a soft dust
BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, softDust.subtract(DOGE.value(1)));
pocket.completeTransaction(sendRequest);
assertEquals(DOGE.getFeeValue().multiply(2), sendRequest.tx.getFee());
}
@Test
public void createTransactionAndBroadcast() throws Exception {
pocket.onConnection(getBlockchainConnection(DOGE));
BitAddress toAddr = BitAddress.from(DOGE, "nZB8PHkfgJvuCJqchSexmfY3ABXa2aE1vp");
Value orgBalance = pocket.getBalance();
BitSendRequest sendRequest = pocket.sendCoinsOffline(toAddr, DOGE.value(AMOUNT_TO_SEND));
sendRequest.shuffleOutputs = false;
sendRequest.feePerTxSize = DOGE.value(0);
pocket.completeTransaction(sendRequest);
// FIXME, mock does not work here
// pocket.broadcastTx(tx);
pocket.addNewTransactionIfNeeded(sendRequest.tx);
assertEquals(orgBalance.subtract(AMOUNT_TO_SEND), pocket.getBalance());
}
// Util methods
////////////////////////////////////////////////////////////////////////////////////////////////
public class MessageComparator implements Comparator<ChildMessage> {
@Override
public int compare(ChildMessage o1, ChildMessage o2) {
String s1 = Utils.HEX.encode(o1.bitcoinSerialize());
String s2 = Utils.HEX.encode(o2.bitcoinSerialize());
return s1.compareTo(s2);
}
}
HashMap<AbstractAddress, AddressStatus> getDummyStatuses() throws AddressMalformedException {
HashMap<AbstractAddress, AddressStatus> status = new HashMap<>(40);
for (int i = 0; i < addresses.size(); i++) {
AbstractAddress address = DOGE.newAddress(addresses.get(i));
status.put(address, new AddressStatus(address, statuses[i]));
}
return status;
}
private HashMap<AbstractAddress, ArrayList<HistoryTx>> getDummyHistoryTXs() throws AddressMalformedException, JSONException {
HashMap<AbstractAddress, ArrayList<HistoryTx>> htxs = new HashMap<>(40);
for (int i = 0; i < statuses.length; i++) {
JSONArray jsonArray = new JSONArray(history[i]);
ArrayList<HistoryTx> list = new ArrayList<>();
for (int j = 0; j < jsonArray.length(); j++) {
list.add(new HistoryTx(jsonArray.getJSONObject(j)));
}
htxs.put(DOGE.newAddress(addresses.get(i)), list);
}
return htxs;
}
private HashMap<AbstractAddress, ArrayList<UnspentTx>> getDummyUnspentTXs() throws AddressMalformedException, JSONException {
HashMap<AbstractAddress, ArrayList<UnspentTx>> utxs = new HashMap<>(40);
for (int i = 0; i < statuses.length; i++) {
JSONArray jsonArray = new JSONArray(unspent[i]);
ArrayList<UnspentTx> list = new ArrayList<>();
for (int j = 0; j < jsonArray.length(); j++) {
list.add(new UnspentTx(jsonArray.getJSONObject(j)));
}
utxs.put(DOGE.newAddress(addresses.get(i)), list);
}
return utxs;
}
private Map<TrimmedOutPoint, OutPointOutput> getDummyUtxoSet() throws AddressMalformedException, JSONException {
final HashMap<TrimmedOutPoint, OutPointOutput> unspentOutputs = new HashMap<>();
for (int i = 0; i < statuses.length; i++) {
BitAddress address = (BitAddress) DOGE.newAddress(addresses.get(i));
JSONArray utxoArray = new JSONArray(unspent[i]);
for (int j = 0; j < utxoArray.length(); j++) {
JSONObject utxoObject = utxoArray.getJSONObject(j);
//"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]",
TrimmedOutPoint outPoint = new TrimmedOutPoint(DOGE, utxoObject.getInt("tx_pos"),
new Sha256Hash(utxoObject.getString("tx_hash")));
TransactionOutput output = new TransactionOutput(DOGE, null,
Coin.valueOf(utxoObject.getLong("value")), address);
OutPointOutput utxo = new OutPointOutput(outPoint, output, false);
unspentOutputs.put(outPoint, utxo);
}
}
return unspentOutputs;
}
private HashMap<Sha256Hash, byte[]> getDummyRawTXs() throws AddressMalformedException, JSONException {
HashMap<Sha256Hash, byte[]> rawTxs = new HashMap<>();
for (String[] tx : txs) {
rawTxs.put(new Sha256Hash(tx[0]), Utils.HEX.decode(tx[1]));
}
return rawTxs;
}
class MockBlockchainConnection implements BitBlockchainConnection {
final HashMap<AbstractAddress, AddressStatus> statuses;
final HashMap<AbstractAddress, ArrayList<HistoryTx>> historyTxs;
final HashMap<AbstractAddress, ArrayList<UnspentTx>> unspentTxs;
final HashMap<Sha256Hash, byte[]> rawTxs;
private CoinType coinType;
MockBlockchainConnection(CoinType coinType) throws Exception {
this.coinType = coinType;
statuses = getDummyStatuses();
historyTxs = getDummyHistoryTXs();
unspentTxs = getDummyUnspentTXs();
rawTxs = getDummyRawTXs();
}
@Override
public void getBlock(int height, TransactionEventListener<BitTransaction> listener) { }
@Override
public void subscribeToBlockchain(TransactionEventListener<BitTransaction> listener) {
listener.onNewBlock(new BlockHeader(coinType, blockTimestamp, blockHeight));
}
@Override
public void subscribeToAddresses(List<AbstractAddress> addresses, TransactionEventListener<BitTransaction> listener) {
for (AbstractAddress a : addresses) {
AddressStatus status = statuses.get(a);
if (status == null) {
status = new AddressStatus(a, null);
}
listener.onAddressStatusUpdate(status);
}
}
@Override
public void getHistoryTx(AddressStatus status, TransactionEventListener<BitTransaction> listener) {
List<HistoryTx> htx = historyTxs.get(status.getAddress());
if (htx == null) {
htx = ImmutableList.of();
}
listener.onTransactionHistory(status, htx);
}
@Override
public void getUnspentTx(AddressStatus status, BitTransactionEventListener listener) {
List<UnspentTx> utx = unspentTxs.get(status.getAddress());
if (utx == null) {
utx = ImmutableList.of();
}
listener.onUnspentTransactionUpdate(status, utx);
}
@Override
public void getTransaction(Sha256Hash txHash, TransactionEventListener<BitTransaction> listener) {
BitTransaction tx = new BitTransaction(coinType, rawTxs.get(txHash));
listener.onTransactionUpdate(tx);
}
@Override
public void broadcastTx(BitTransaction tx, TransactionEventListener<BitTransaction> listener) {
// List<AddressStatus> newStatuses = new ArrayList<AddressStatus>();
// Random rand = new Random();
// byte[] randBytes = new byte[32];
// // Get spent outputs and modify statuses
// for (TransactionInput txi : tx.getInputs()) {
// UnspentTx unspentTx = new UnspentTx(
// txi.getOutpoint(), txi.getValue().value, 0);
//
// for (Map.Entry<Address, ArrayList<UnspentTx>> entry : utxs.entrySet()) {
// if (entry.getValue().remove(unspentTx)) {
// rand.nextBytes(randBytes);
// AddressStatus newStatus = new AddressStatus(entry.getKey(), Utils.HEX.encode(randBytes));
// statuses.put(entry.getKey(), newStatus);
// newStatuses.add(newStatus);
// }
// }
// }
//
// for (TransactionOutput txo : tx.getOutputs()) {
// if (txo.getAddressFromP2PKHScript(coinType) != null) {
// Address address = txo.getAddressFromP2PKHScript(coinType);
// if (addresses.contains(address.toString())) {
// AddressStatus newStatus = new AddressStatus(address, tx.getHashAsString());
// statuses.put(address, newStatus);
// newStatuses.add(newStatus);
// if (!utxs.containsKey(address)) {
// utxs.put(address, new ArrayList<UnspentTx>());
// }
// ArrayList<UnspentTx> unspentTxs = utxs.get(address);
// unspentTxs.add(new UnspentTx(txo.getOutPointFor(),
// txo.getValue().value, 0));
// if (!historyTxs.containsKey(address)) {
// historyTxs.put(address, new ArrayList<HistoryTx>());
// }
// ArrayList<HistoryTx> historyTxes = historyTxs.get(address);
// historyTxes.add(new HistoryTx(txo.getOutPointFor(), 0));
// }
// }
// }
//
// rawTxs.put(tx.getHash(), tx.bitcoinSerialize());
//
// for (AddressStatus newStatus : newStatuses) {
// listener.onAddressStatusUpdate(newStatus);
// }
}
@Override
public boolean broadcastTxSync(BitTransaction tx) {
return false;
}
@Override
public void ping(String versionString) {}
@Override
public void addEventListener(ConnectionEventListener listener) {
}
@Override
public void resetConnection() {
}
@Override
public void stopAsync() {
}
@Override
public boolean isActivelyConnected() {
return false;
}
@Override
public void startAsync() {
}
}
private MockBlockchainConnection getBlockchainConnection(CoinType coinType) throws Exception {
return new MockBlockchainConnection(coinType);
}
// Mock data
long blockTimestamp = 1411000000l;
int blockHeight = 200000;
List<String> addresses = ImmutableList.of(
"nnfP8VuPfZXhNtMDzvX1bKurzcV1k7HNrQ",
"nf4AUKiaGdx4GTbbh222KvtuCbAuvbcdE2",
"npGkmbWtdWybFNSZQXUK6zZxbEocMtrTzz",
"nVaN45bbs6AUc1EUpP71hHGBGb2qciNrJc",
"nrdHFZP1AfdKBrjsSQmwFm8R2i2mzMef75",
"niGZgfbhFYn6tJqksmC8CnzSRL1GHNsu7e",
"nh6w8yu1zoKYoT837ffkVmuPjTaP69Pc5E",
"nbyMgmEghsL9tpk7XfdH9gLGudh6Lrbbuf",
"naX9akzYuWY1gKbcZo3t36aBKc1gqbzgSs",
"nqcPVTGeAfCowELB2D5PdVF3FWFjFtkkFf",
"nd4vVvPTpp2LfcsMPsmG3Dh7MFAsqRHp4g",
"nVK4Uz5Sf56ygrr6RiwXcRvH8AuUVbjjHi",
"nbipkRwT1NCSXZSrm8uAAEgQAA2s2NWMkG",
"nZU6QAMAdCQcVDxEmL7GEY6ykFm8m6u6am",
"nbFqayssM5s7hLjLFwf2d95JXKRWBk2pBH",
"nacZfcNgVi47hamLscWdUGQhUQGGpSdgq8",
"niiMT7ZYeFnaLPYtqQFBBX1sP3dT5JtcEw",
"ns6GyTaniLWaiYrvAf5tk4D8tWrbcCLGyj",
"nhdwQfptLTzLJGbLF3vvtqyBaqPMPecDmE",
"neMUAGeTzwxLbSkXMsdmWf1fTKS1UsJjXY",
"nXsAMeXxtpx8jaxnU3Xv9ZQ6ZcRcD1xYhR",
"ns35rKnnWf6xP3KSj5WPkMCVVaADGi6Ndk",
"nk4wcXYBEWs5HkhNLsuaQJoAjJHoK6SQmG",
"npsJQWu8fsALoTPum8D4j8FDkyeusk8fU8",
"nZNhZo4Vz3DnwQGPL3SJTZgUw2Kh4g9oay",
"nnxDTYB8WMHMgLnCY2tuaEtysvdhRnWehZ",
"nb2iaDXG1EqkcE47H87WQFkQNkeVK66Z21",
"nWHAkpn2DB3DJRsbiK3vpbigoa3M2uVuF8",
"nViKdC7Gm6TMmCuWTBwVE9i4rJhyfwbfqg",
"nZQV5BifbGPzaxTrB4efgHruWH5rufemqP",
"nVvZaLvnkCVAzpLYPoHeqU4w9zJ5yrZgUn",
"nrMp6pRCk98WYWkCWq9Pqthz9HbpQu8BT3",
"nnA3aYsLqysKT6gAu1dr4EKm586cmKiRxS",
"nVfcVgMY7DL6nqoSxwJy7B7hKXirQwj6ic",
"ni4oAzi6nCVuEdjoHyVMVKWb1DqTd3qY3H",
"nnpf3gx442yomniRJPMGPapgjHrraPZXxJ",
"nkuFnF8wUmHFkMycaFMvyjBoiMeR5KBKGd",
"nXKccwjaUyrQkLrdqKT6aq6cDiFgBBVgNz",
"nZMSNsXSAL7i1YD6KP5FrhATuZ2CWvnxqR",
"nUEkQ3LjH9m4ScbP6NGtnAdnnUsdtWv99Q"
);
String[] statuses = {
"fe7c109d8bd90551a406cf0b3499117db04bc9c4f48e1df27ac1cf3ddcb3d464",
"8a53babd831c6c3a857e20190e884efe75a005bdd7cd273c4f27ab1b8ec81c2d",
"86bc2f0cf0112fd59c9aadfe5c887062c21d7a873db260dff68dcfe4417fe212",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
"64a575b5605671831185ca715e8197f0455733e721a6c6c5b8add31bd6eabbe9",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
};
String[] unspent = {
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 1, \"value\": 1000000000, \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"tx_pos\": 0, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 2, \"value\": 500000000, \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"tx_pos\": 0, \"value\": 1000000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 3, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 4, \"value\": 1000000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 11, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 12, \"value\": 1000000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 13, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 6, \"value\": 500000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 7, \"value\": 1000000000, \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 8, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 9, \"value\": 500000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"tx_pos\": 10, \"value\": 1000000000, \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]"
};
String[] history = {
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}, {\"tx_hash\": \"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[{\"tx_hash\": \"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f\", \"height\": 160267}]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]",
"[]"
};
String[][] txs = {
{"ef74da273e8a77e2d60b707414fb7e0ccb35c7b1b936800a49fe953195b1799f", "0100000001b8778dff640ccb144346d9db48201639b2707a0cc59e19672d2dd76cc6d1a5a6010000006b48304502210098d2e5b8a6c72442430bc09f2f4bcb56612c5b9e5eee821d65b412d099bb723402204f7f008ac052e5d7be0ab5b0c85ea5e627d725a521bd9e9b193d1fdf81c317a0012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0e0065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00ca9a3b000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac0065cd1d000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac0065cd1d000000001976a9140f2b1e5b376e22c5d1e635233eb90cf50ad9095188ac00ca9a3b000000001976a914f612ffd50b6a69df5e34ee0c5b529dfaaedca03d88ac00f633bce60000001976a914937258e3a8c463ec07e78ce62326c488170ad25e88ac0065cd1d000000001976a9142848ad5ff4cc32df3649646017c47bc04e8d211788ac00ca9a3b000000001976a914fa937737a6df2b8a5e39cce8b0bdd9510683023a88ac0065cd1d000000001976a914ae248a5d710143b6b309aaab9ce17059536e2aa388ac0065cd1d000000001976a91438d6eb11eca405be497a7183c50e437851425e0088ac00ca9a3b000000001976a91410ac6b2704146b50a1dd8f6df70736856ebf8b3488ac0065cd1d000000001976a914456816dccb3a4f33ae2dbd3ba623997075d5c73d88ac00ca9a3b000000001976a91452957c44e5bee9a60402a739fc8959c2850ea98488ac0065cd1d000000001976a914fb2dffa402d05f74335d137e21e41d8920c745fb88ac00000000"},
{"89a72ba4732505ce9b09c30668db985952701252ce0adbd7c43336396697d6ae", "01000000011a656d67706db286d1e6fad57eb4f411cb14f8880cea8348da339b9d434a5ec7050000006a47304402201d69fddb269b53aa742ff6437a45adb4ca5c59f666c9b4eabc4a0c7a6e6f4c0f022015a747b7a6d9371a4020f5b396dcd094b0f36af3fc82e95091da856181912dfa012102c9a8d5b2f768afe30ee772d185e7a61f751be05649a79508b38a2be8824adec3ffffffff020065cd1d000000001976a914ca983c2da690de3cdc693ca013d93e569810c52c88ac00b07098e60000001976a9141630d812e219e6bcbe494eb96f7a7900c216ad5d88ac00000000"},
{"edaf445288d8e65cf7963bc8047c90f53681acaadc5ccfc5ecc67aedbd73cddb", "010000000164a3990893c012b20287d43d1071ac26f4b93648ff4213db6da6979beed6b7dc010000006b48304502210086ac11d4a8146b4176a72059960690c72a9776468cd671fd07c064b51f24961d02205bcf008d6995014f3cfd79100ee9beab5688c88cca15c5cea38b769563785d900121036530415a7b3b9c5976f26a63a57d119ab39491762121723c773399a2531a1bd7ffffffff020065cd1d000000001976a91477263ab93a49b1d3eb5887187704cdb82e1c60ce88ac006aad74e60000001976a914e5616848352c328c9f61b167eb1b0fde39b5cb6788ac00000000"},
{"81a1f0f8242d5e71e65ff9e8ec51e8e85d641b607d7f691c1770d4f25918ebd7", "010000000141c217dfea3a1d8d6a06e9d3daf75b292581f652256d73a7891e5dc9c7ee3cca000000006a47304402205cce451228f98fece9645052546b82c2b2d425a4889b03999001fababfc7f4690220583b2189faef07d6b0191c788301cfab1b3f47ffe2c403d632b92c6dde27e14f012102d26e423c9da9ff4a7bf6b756b2dafb75cca34fbd34f64c4c3b77c37179c5bba2ffffffff0100ca9a3b000000001976a914dc40fbbc8caa1f7617d275aec9a3a14ce8d8652188ac00000000"}
};
}
| openwalletGH/openwallet-android | core/src/test/java/com/openwallet/core/wallet/WalletPocketHDTest.java |
45,899 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class SocksAuthRequestTest {
@Test
public void testConstructorParamsAreNotNull() {
try {
new SocksAuthRequest(null, "");
} catch (Exception e) {
assertTrue(e instanceof NullPointerException);
}
try {
new SocksAuthRequest("", null);
} catch (Exception e) {
assertTrue(e instanceof NullPointerException);
}
}
@Test
public void testUsernameOrPasswordIsNotAscii() {
try {
new SocksAuthRequest("παράδειγμα.δοκιμή", "password");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
new SocksAuthRequest("username", "παράδειγμα.δοκιμή");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
@Test
public void testUsernameOrPasswordLengthIsLessThan255Chars() {
try {
new SocksAuthRequest(
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword",
"password");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
new SocksAuthRequest("password",
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword" +
"passwordpasswordpasswordpasswordpasswordpasswordpassword");
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
}
}
| wuyinxian124/netty4.0.27Learn | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksAuthRequestTest.java |
45,900 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import sun.net.util.IPAddressUtil;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksCmdType cmdType,
SocksAddressType addressType,
String host,
int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host +
" port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
EmbeddedChannel embedder = new EmbeddedChannel(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.addressType() == SocksAddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocksRequest);
} else {
msg = (SocksCmdRequest) embedder.readInbound();
assertSame(msg.cmdType(), cmdType);
assertSame(msg.addressType(), addressType);
assertEquals(msg.host(), host);
assertEquals(msg.port(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1", };
int[] ports = {0, 32769, 65535 };
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() {
String[] hosts = {SocksCommonUtils.ipv6toStr(IPAddressUtil.textToNumericFormatV6("::1"))};
int[] ports = {0, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {0, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (SocksCmdType cmdType : SocksCmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.UNKNOWN, host, port);
}
}
}
| jmhodges/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,901 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedByteChannel;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.net.util.IPAddressUtil;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final Logger logger = LoggerFactory.getLogger(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksMessage.CmdType cmdType, SocksMessage.AddressType addressType, String host, int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host + " port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
EmbeddedByteChannel embedder = new EmbeddedByteChannel(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.getAddressType() == SocksMessage.AddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocksRequest);
} else {
msg = (SocksCmdRequest) embedder.readInbound();
assertSame(msg.getCmdType(), cmdType);
assertSame(msg.getAddressType(), addressType);
assertEquals(msg.getHost(), host);
assertEquals(msg.getPort(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1",};
int[] ports = {0, 32769, 65535 };
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() {
String[] hosts = {SocksCommonUtils.ipv6toStr(IPAddressUtil.textToNumericFormatV6("::1"))};
int[] ports = {0, 32769, 65535};
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {0, 32769, 65535};
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.UNKNOWN, host, port);
}
}
}
| la3lma/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,902 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import sun.net.util.IPAddressUtil;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksCmdType cmdType,
SocksAddressType addressType,
String host,
int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host +
" port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
EmbeddedChannel embedder = new EmbeddedChannel(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.addressType() == SocksAddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocksRequest);
} else {
msg = embedder.readInbound();
assertSame(msg.cmdType(), cmdType);
assertSame(msg.addressType(), addressType);
assertEquals(msg.host(), host);
assertEquals(msg.port(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1", };
int[] ports = {0, 32769, 65535 };
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() {
String[] hosts = {SocksCommonUtils.ipv6toStr(IPAddressUtil.textToNumericFormatV6("::1"))};
int[] ports = {0, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {0, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (SocksCmdType cmdType : SocksCmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.UNKNOWN, host, port);
}
}
}
| jimma/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,903 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import sun.net.util.IPAddressUtil;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksCmdType cmdType,
SocksAddressType addressType,
String host,
int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host +
" port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
EmbeddedChannel embedder = new EmbeddedChannel(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.addressType() == SocksAddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocksRequest);
} else {
msg = embedder.readInbound();
assertSame(msg.cmdType(), cmdType);
assertSame(msg.addressType(), addressType);
assertEquals(msg.host(), host);
assertEquals(msg.port(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1", };
int[] ports = {1, 32769, 65535 };
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() {
String[] hosts = {SocksCommonUtils.ipv6toStr(IPAddressUtil.textToNumericFormatV6("::1"))};
int[] ports = {1, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {1, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (SocksCmdType cmdType : SocksCmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.UNKNOWN, host, port);
}
}
}
| softprops/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,904 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.jboss.netty.handler.codec.socks;
import org.jboss.netty.handler.codec.embedder.DecoderEmbedder;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.junit.Test;
import sun.net.util.IPAddressUtil;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksMessage.CmdType cmdType,
SocksMessage.AddressType addressType, String host, int port) throws Exception {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: "
+ host + " port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
DecoderEmbedder<SocksRequest> embedder = new DecoderEmbedder<SocksRequest>(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.getAddressType() == SocksMessage.AddressType.UNKNOWN) {
assertTrue(embedder.poll() instanceof UnknownSocksRequest);
} else {
msg = (SocksCmdRequest) embedder.poll();
assertSame(msg.getCmdType(), cmdType);
assertSame(msg.getAddressType(), addressType);
assertEquals(msg.getHost(), host);
assertEquals(msg.getPort(), port);
}
assertNull(embedder.poll());
}
@Test
public void testCmdRequestDecoderIPv4() throws Exception{
String[] hosts = { "127.0.0.1" };
int[] ports = {1, 32769, 65535 };
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() throws Exception{
String[] hosts = { SocksCommonUtils.ipv6toStr(IPAddressUtil.textToNumericFormatV6("::1")) };
int[] ports = {1, 32769, 65535};
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() throws Exception{
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {1, 32769, 65535};
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() throws Exception{
String host = "google.com";
int port = 80;
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.UNKNOWN, host, port);
}
}
}
| iMasonite/netty | src/test/java/org/jboss/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,905 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedByteChannel;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.net.util.IPAddressUtil;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final Logger logger = LoggerFactory.getLogger(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksMessage.CmdType cmdType, SocksMessage.AddressType addressType, String host, int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host + " port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
EmbeddedByteChannel embedder = new EmbeddedByteChannel(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.addressType() == SocksMessage.AddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocksRequest);
} else {
msg = (SocksCmdRequest) embedder.readInbound();
assertSame(msg.cmdType(), cmdType);
assertSame(msg.addressType(), addressType);
assertEquals(msg.host(), host);
assertEquals(msg.port(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1",};
int[] ports = {0, 32769, 65535 };
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() {
String[] hosts = {SocksCommonUtils.ipv6toStr(IPAddressUtil.textToNumericFormatV6("::1"))};
int[] ports = {0, 32769, 65535};
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {0, 32769, 65535};
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (SocksMessage.CmdType cmdType : SocksMessage.CmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksMessage.AddressType.UNKNOWN, host, port);
}
}
}
| jeje/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,906 | package com.sobot.chat.utils;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.URLSpan;
import android.widget.TextView;
import com.sobot.chat.core.HttpUtils;
import com.sobot.chat.widget.LinkMovementClickMethod;
import com.sobot.chat.widget.emoji.InputHelper;
import com.sobot.chat.widget.html.SobotCustomTagHandler;
import com.sobot.chat.widget.rich.EmailSpan;
import com.sobot.chat.widget.rich.MyURLSpan;
import com.sobot.chat.widget.rich.PhoneSpan;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* loaded from: source-8303388-dex2jar.jar:com/sobot/chat/utils/HtmlTools.class */
public class HtmlTools {
public static final String GOOD_IRI_CHAR = "a-zA-Z0-9 -\ud7ff豈-\ufdcfﷰ-\uffef";
public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL = "(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))";
private static HtmlTools instance;
private Context context;
private String textImagePath;
public static Pattern WEB_URL3 = Pattern.compile("(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]");
public static final Pattern WEB_URL2 = Pattern.compile("(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?");
public static final Pattern WEB_URL = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?((?:(?:[a-zA-Z0-9 -\ud7ff豈-\ufdcfﷰ-\uffef][a-zA-Z0-9 -\ud7ff豈-\ufdcfﷰ-\uffef\\-]{0,64}\\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9 -\ud7ff豈-\ufdcfﷰ-\uffef\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?(?:\\b|$)");
public static final Pattern EMAIL_ADDRESS = Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}(\\.[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25})+");
public static Pattern PHONE_NUMBER = Pattern.compile("\\d{3}-\\d{8}|\\d{3}-\\d{7}|\\d{4}-\\d{8}|\\d{4}-\\d{7}|1+[34578]+\\d{9}|\\+\\d{2}1+[34578]+\\d{9}|400\\d{7}|400-\\d{3}-\\d{4}|\\d{12}|\\d{11}|\\d{10}|\\d{8}|\\d{7}");
public static final Pattern EMOJI = Pattern.compile("\\[(([一-龥]+)|([a-zA-z]+))\\]");
public static final Pattern EMOJI_NUMBERS = Pattern.compile("\\[[(0-9)]+\\]");
private HtmlTools(Context context) {
this.context = context.getApplicationContext();
}
public static HtmlTools getInstance(Context context) {
if (instance == null) {
instance = new HtmlTools(context.getApplicationContext());
}
return instance;
}
public static Pattern getPhoneNumberPattern() {
return PHONE_NUMBER;
}
public static Pattern getWebUrl() {
return WEB_URL3;
}
public static boolean isHasPatterns(String str) {
if (TextUtils.isEmpty(str)) {
return false;
}
if (getWebUrl().matcher(str.toString()).matches()) {
return true;
}
LogUtils.i("URL 非法,请输入有效的URL链接:" + str);
return false;
}
public static void parseLinkText(Context context, TextView textView, Spanned spanned, int i, boolean z) {
if (spanned instanceof Spannable) {
Spannable spannable = (Spannable) spanned;
Matcher matcher = EMAIL_ADDRESS.matcher(spannable);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
if (((URLSpan[]) spannable.getSpans(start, end, URLSpan.class)).length == 0) {
spannable.setSpan(new EmailSpan(context.getApplicationContext(), matcher.group(), i), start, end, 33);
}
}
Matcher matcher2 = getWebUrl().matcher(spannable);
while (matcher2.find()) {
int start2 = matcher2.start();
int end2 = matcher2.end();
if (((URLSpan[]) spannable.getSpans(start2, end2, URLSpan.class)).length == 0) {
spannable.setSpan(new MyURLSpan(context.getApplicationContext(), matcher2.group(), i, true), start2, end2, 33);
}
}
Matcher matcher3 = getPhoneNumberPattern().matcher(spannable);
while (matcher3.find()) {
int start3 = matcher3.start();
int end3 = matcher3.end();
if (((URLSpan[]) spannable.getSpans(start3, end3, URLSpan.class)).length == 0) {
spannable.setSpan(new PhoneSpan(context.getApplicationContext(), matcher3.group(), i), start3, end3, 33);
}
}
int length = spanned.length();
URLSpan[] uRLSpanArr = (URLSpan[]) spannable.getSpans(0, length, URLSpan.class);
URLSpan[] uRLSpanArr2 = spanned != null ? (URLSpan[]) spanned.getSpans(0, length, URLSpan.class) : new URLSpan[0];
if (uRLSpanArr.length == 0 && uRLSpanArr2.length == 0) {
textView.setText(spannable);
return;
}
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(spanned);
for (URLSpan uRLSpan : uRLSpanArr2) {
spannableStringBuilder.removeSpan(uRLSpan);
spannableStringBuilder.setSpan(new MyURLSpan(context.getApplicationContext(), uRLSpan.getURL(), i, z), spanned.getSpanStart(uRLSpan), spanned.getSpanEnd(uRLSpan), 33);
}
textView.setText(spannableStringBuilder);
}
}
public static void setPhoneNumberPattern(Pattern pattern) {
PHONE_NUMBER = pattern;
}
public static void setWebUrl(Pattern pattern) {
WEB_URL3 = pattern;
}
public Spanned formatRichTextWithPic(final TextView textView, final String str, final int i) {
return Html.fromHtml(str.replace("span", SobotCustomTagHandler.NEW_SPAN), new Html.ImageGetter() { // from class: com.sobot.chat.utils.HtmlTools.2
@Override // android.text.Html.ImageGetter
public Drawable getDrawable(String str2) {
if (TextUtils.isEmpty(str2)) {
return null;
}
HtmlTools htmlTools = HtmlTools.this;
htmlTools.textImagePath = CommonUtils.getSDCardRootPath(htmlTools.context);
String str3 = HtmlTools.this.textImagePath + String.valueOf(str2.hashCode());
if (!new File(str3).exists()) {
LogUtils.i(str3 + " Do not eixts");
if (str2.startsWith("https://") || str2.startsWith("http://")) {
HtmlTools.this.loadPic(textView, str2, str, str3, i);
return null;
}
return null;
}
LogUtils.i(" 网络下载 文本中的图片信息 " + str3 + " eixts");
Drawable createFromPath = Drawable.createFromPath(str3);
if (createFromPath != null) {
LogUtils.i(" 图文并茂中 图片的 大小 width: " + createFromPath.getIntrinsicWidth() + "--height:" + createFromPath.getIntrinsicWidth());
createFromPath.setBounds(0, 0, createFromPath.getIntrinsicWidth() * 4, createFromPath.getIntrinsicHeight() * 4);
}
return createFromPath;
}
}, new SobotCustomTagHandler(this.context, textView.getTextColors()));
}
public String getHTMLStr(String str) {
if (TextUtils.isEmpty(str)) {
return "";
}
return Pattern.compile("<[^>]+>", 2).matcher(Pattern.compile("<br/>", 2).matcher(str).replaceAll("\n")).replaceAll("");
}
public void loadPic(final TextView textView, String str, final String str2, String str3, final int i) {
HttpUtils.getInstance().download(str, new File(str3), null, new HttpUtils.FileCallBack() { // from class: com.sobot.chat.utils.HtmlTools.1
@Override // com.sobot.chat.core.HttpUtils.FileCallBack
public void inProgress(int i2) {
LogUtils.i(" 文本图片的下载进度" + i2);
}
@Override // com.sobot.chat.core.HttpUtils.FileCallBack
public void onError(Exception exc, String str4, int i2) {
LogUtils.i(" 文本图片的下载失败", exc);
}
@Override // com.sobot.chat.core.HttpUtils.FileCallBack
public void onResponse(File file) {
HtmlTools.this.setRichText(textView, str2, i);
}
});
}
public void setRichText(TextView textView, String str, int i) {
if (TextUtils.isEmpty(str)) {
return;
}
String str2 = str;
if (str.contains("<p>")) {
str2 = str.replaceAll("<p>", "").replaceAll("</p>", "<br/>").replaceAll("\n", "<br/>");
}
while (str2.length() > 5 && "<br/>".equals(str2.substring(str2.length() - 5, str2.length()))) {
str2 = str2.substring(0, str2.length() - 5);
}
String str3 = str2;
if (!TextUtils.isEmpty(str2)) {
str3 = str2;
if (str2.length() > 0) {
str3 = str2;
if ("\n".equals(str2.substring(str2.length() - 1, str2.length()))) {
int i2 = 0;
while (true) {
int i3 = i2;
str3 = str2;
if (i3 >= str2.length()) {
break;
}
str3 = str2;
if (str2.lastIndexOf("\n") != str2.length() - 1) {
break;
}
str2 = str2.substring(0, str2.length() - 1);
i2 = i3 + 1;
}
}
}
}
textView.setMovementMethod(LinkMovementClickMethod.getInstance());
parseLinkText(this.context, textView, InputHelper.displayEmoji(this.context.getApplicationContext(), formatRichTextWithPic(textView, str3.replace("\n", "<br/>"), i)), i, false);
}
public void setRichText(TextView textView, String str, int i, boolean z) {
String str2 = str;
if (TextUtils.isEmpty(str)) {
return;
}
while (!TextUtils.isEmpty(str2) && str2.length() > 5 && "<br/>".equals(str2.substring(0, 5))) {
str2 = str2.substring(5, str2.length());
}
String str3 = str2;
if (!TextUtils.isEmpty(str2)) {
str3 = str2;
if (str2.length() > 5) {
str3 = str2;
if ("<br/>".equals(str2.substring(str2.length() - 5, str2.length()))) {
str3 = str2.substring(0, str2.length() - 5);
}
}
}
textView.setMovementMethod(LinkMovementClickMethod.getInstance());
textView.setFocusable(false);
parseLinkText(this.context, textView, InputHelper.displayEmoji(this.context.getApplicationContext(), formatRichTextWithPic(textView, str3.replace("\n", "<br />"), i)), i, z);
}
public void setRichTextViewText(TextView textView, String str, int i) {
if (TextUtils.isEmpty(str)) {
return;
}
String str2 = str;
if (str.contains("\n")) {
str2 = str.replaceAll("\n", "<br/>");
}
textView.setMovementMethod(LinkMovementClickMethod.getInstance());
parseLinkText(this.context, textView, InputHelper.displayEmoji(this.context.getApplicationContext(), formatRichTextWithPic(textView, str2.replace("\n", "<br/>"), i)), i, false);
}
}
| lack21115/blued-7.20.6-src | com/sobot/chat/utils/HtmlTools.java |
45,907 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksCmdType cmdType,
SocksAddressType addressType,
String host,
int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host +
" port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
EmbeddedChannel embedder = new EmbeddedChannel(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.addressType() == SocksAddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocksRequest);
} else {
msg = embedder.readInbound();
assertSame(msg.cmdType(), cmdType);
assertSame(msg.addressType(), addressType);
assertEquals(msg.host(), host);
assertEquals(msg.port(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1", };
int[] ports = {1, 32769, 65535 };
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() throws UnknownHostException {
String[] hosts = {SocksCommonUtils.ipv6toStr(InetAddress.getByName("::1").getAddress())};
int[] ports = {1, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {1, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (SocksCmdType cmdType : SocksCmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.UNKNOWN, host, port);
}
}
}
| Darkthas/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,908 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import java.net.UnknownHostException;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksCmdType cmdType,
SocksAddressType addressType,
String host,
int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host +
" port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
EmbeddedChannel embedder = new EmbeddedChannel(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.addressType() == SocksAddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocksRequest);
} else {
msg = embedder.readInbound();
assertSame(msg.cmdType(), cmdType);
assertSame(msg.addressType(), addressType);
assertEquals(msg.host(), host);
assertEquals(msg.port(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1", };
int[] ports = {1, 32769, 65535 };
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() throws UnknownHostException {
String[] hosts = {SocksCommonUtils.ipv6toStr(SocketUtils.addressByName("::1").getAddress())};
int[] ports = {1, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {1, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (SocksCmdType cmdType : SocksCmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.UNKNOWN, host, port);
}
}
}
| expansion/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,909 | package de.malkusch.whoisServerList.compiler.helper.converter;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import org.junit.Test;
import de.malkusch.whoisServerList.compiler.exception.WhoisServerListException;
import de.malkusch.whoisServerList.compiler.helper.converter.DocumentToStringIteratorConvertor;
import de.malkusch.whoisServerList.compiler.helper.converter.InputStreamToDocumentConverter;
import de.malkusch.whoisServerList.compiler.list.iana.IanaDomainListFactory;
public class DocumentToStringIteratorConvertorTest {
@Test
public void testConvert() throws IOException, WhoisServerListException {
String[] expectedTLDs = { ".ac", ".academy", ".axa", ".vn", ".vodka",
".测试", ".परीक्षा", ".在线", ".한국", ".ভারত", ".موقع", ".বাংলা",
".москва", ".테스트", ".טעסט", ".భారత్", ".ලංකා", ".ભારત",
".भारत", ".آزمایشی", ".பரிட்சை", ".δοκιμή", ".إختبار", ".台灣",
".мон", ".الجزائر", ".المغرب", ".السعودية", ".سودان",
".مليسيا", ".شبكة", ".გე", ".ไทย", ".سورية", ".تونس", ".みんな",
".مصر", ".இந்தியா", ".xxx", ".yachts", ".zw" };
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/compiler.properties"));
InputStream ianaList = getClass().getResourceAsStream(
"/iana-list-excerpt.html");
InputStreamToDocumentConverter documentConverter = new InputStreamToDocumentConverter(
properties
.getProperty(IanaDomainListFactory.PROPERTY_LIST_CHARSET));
DocumentToStringIteratorConvertor<InputStream> converter = new DocumentToStringIteratorConvertor<>(
properties
.getProperty(IanaDomainListFactory.PROPERTY_LIST_TLD_XPATH),
documentConverter);
ArrayList<String> tlds = new ArrayList<>();
for (String tld : converter.convert(ianaList)) {
tlds.add(tld);
}
assertArrayEquals(expectedTLDs, tlds.toArray());
}
}
| whois-server-list/whois-server-list-maven-plugin | src/test/java/de/malkusch/whoisServerList/compiler/helper/converter/DocumentToStringIteratorConvertorTest.java |
45,910 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socksx.v5;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import sun.net.util.IPAddressUtil;
import static org.junit.Assert.*;
public class Socks5CmdRequestDecoderTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(Socks5CmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(Socks5CmdType cmdType,
Socks5AddressType addressType,
String host,
int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host +
" port: " + port);
Socks5CmdRequest msg = new Socks5CmdRequest(cmdType, addressType, host, port);
Socks5CmdRequestDecoder decoder = new Socks5CmdRequestDecoder();
EmbeddedChannel embedder = new EmbeddedChannel(decoder);
Socks5CommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.addressType() == Socks5AddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocks5Request);
} else {
msg = embedder.readInbound();
assertSame(msg.cmdType(), cmdType);
assertSame(msg.addressType(), addressType);
assertEquals(msg.host(), host);
assertEquals(msg.port(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1", };
int[] ports = {1, 32769, 65535 };
for (Socks5CmdType cmdType : Socks5CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, Socks5AddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() {
String[] hosts = { Socks5CommonUtils.ipv6toStr(IPAddressUtil.textToNumericFormatV6("::1"))};
int[] ports = {1, 32769, 65535};
for (Socks5CmdType cmdType : Socks5CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, Socks5AddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {1, 32769, 65535};
for (Socks5CmdType cmdType : Socks5CmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, Socks5AddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (Socks5CmdType cmdType : Socks5CmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, Socks5AddressType.UNKNOWN, host, port);
}
}
}
| bfritz/netty | codec-socks/src/test/java/io/netty/handler/codec/socksx/v5/Socks5CmdRequestDecoderTest.java |
45,911 | package com.facebook.text.linkify;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.text.util.Linkify.MatchFilter;
import android.text.util.Linkify.TransformFilter;
import android.util.Patterns;
import android.webkit.WebView;
import android.widget.TextView;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* compiled from: deltaMarkUnread */
class FbLinkify {
private static final Pattern f17607a = Pattern.compile("((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?((?:(?:[a-zA-Z0-9 -豈-﷏ﷰ-\\_][a-zA-Z0-9 -豈-﷏ﷰ-\\_\\-]{0,64}\\.)+(?:(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])|(?:biz|b[abdefghijmnorstvwyz])|(?:cat|com|coop|c[acdfghiklmnoruvxyz])|d[ejkmoz]|(?:edu|e[cegrstu])|f[ijkmor]|(?:gov|g[abdefghilmnpqrstuwy])|h[kmnrtu]|(?:info|int|i[delmnoqrst])|(?:jobs|j[emop])|k[eghimnprwyz]|l[abcikrstuvy]|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])|(?:name|net|n[acefgilopruz])|(?:org|om)|(?:pro|p[aefghklmnrstwy])|qa|r[eosuw]|s[abcdeghijklmnortuvyz]|(?:tel|travel|t[cdfghjklmnoprtvwz])|u[agksyz]|v[aceginu]|w[fs]|(?:δοκιμή|испытание|рф|срб|טעסט|آزمایشی|إختبار|الاردن|الجزائر|السعودية|المغرب|امارات|بھارت|تونس|سورية|فلسطين|قطر|مصر|परीक्षा|भारत|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|சிங்கப்பூர்|பரிட்சை|భారత్|ලංකා|ไทย|テスト|中国|中國|台湾|台灣|新加坡|测试|測試|香港|테스트|한국|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)|y[et]|z[amw]))|(?:(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[0-9])))(?:\\:\\d{1,5})?)(\\/(?:(?:[a-zA-Z0-9 -豈-﷏ﷰ-\\;\\/\\?\\:\\@\\&\\=\\#\\~\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?(?:\\b|$)");
/* compiled from: deltaMarkUnread */
final class C12861 implements Comparator<LinkSpec> {
C12861() {
}
public final int compare(Object obj, Object obj2) {
LinkSpec linkSpec = (LinkSpec) obj;
LinkSpec linkSpec2 = (LinkSpec) obj2;
if (linkSpec.f17609b < linkSpec2.f17609b) {
return -1;
}
if (linkSpec.f17609b > linkSpec2.f17609b) {
return 1;
}
if (linkSpec.f17610c < linkSpec2.f17610c) {
return 1;
}
if (linkSpec.f17610c <= linkSpec2.f17610c) {
return 0;
}
return -1;
}
public final boolean equals(Object obj) {
return false;
}
}
FbLinkify() {
}
static final boolean m25592a(Spannable spannable, int i) {
if (i == 0) {
return false;
}
URLSpan[] uRLSpanArr = (URLSpan[]) spannable.getSpans(0, spannable.length(), URLSpan.class);
for (int length = uRLSpanArr.length - 1; length >= 0; length--) {
spannable.removeSpan(uRLSpanArr[length]);
}
ArrayList arrayList = new ArrayList();
if ((i & 1) != 0) {
Spannable spannable2 = spannable;
m25591a(arrayList, spannable2, f17607a, new String[]{"http://", "https://", "rtsp://"}, Linkify.sUrlMatchFilter, null);
}
if ((i & 2) != 0) {
m25591a(arrayList, spannable, Patterns.EMAIL_ADDRESS, new String[]{"mailto:"}, null, null);
}
if ((i & 4) != 0) {
spannable2 = spannable;
m25591a(arrayList, spannable2, Patterns.PHONE, new String[]{"tel:"}, Linkify.sPhoneNumberMatchFilter, Linkify.sPhoneNumberTransformFilter);
}
if ((i & 8) != 0) {
m25590a(arrayList, spannable);
}
m25589a(arrayList);
if (arrayList.isEmpty()) {
return false;
}
Iterator it = arrayList.iterator();
while (it.hasNext()) {
LinkSpec linkSpec = (LinkSpec) it.next();
String str = linkSpec.f17608a;
spannable.setSpan(new URLSpan(str), linkSpec.f17609b, linkSpec.f17610c, 33);
}
return true;
}
static final boolean m25593a(TextView textView, int i) {
if (i == 0) {
return false;
}
CharSequence text = textView.getText();
if (!(text instanceof Spannable)) {
Spannable valueOf = SpannableString.valueOf(text);
if (!m25592a(valueOf, i)) {
return false;
}
m25588a(textView);
textView.setText(valueOf);
return true;
} else if (!m25592a((Spannable) text, i)) {
return false;
} else {
m25588a(textView);
return true;
}
}
private static final void m25588a(TextView textView) {
MovementMethod movementMethod = textView.getMovementMethod();
if ((movementMethod == null || !(movementMethod instanceof LinkMovementMethod)) && textView.getLinksClickable()) {
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
private static final String m25587a(String str, String[] strArr, Matcher matcher, TransformFilter transformFilter) {
String transformUrl;
boolean z = true;
if (transformFilter != null) {
transformUrl = transformFilter.transformUrl(matcher, str);
} else {
transformUrl = str;
}
for (int i = 0; i < strArr.length; i++) {
if (transformUrl.regionMatches(true, 0, strArr[i], 0, strArr[i].length())) {
if (!transformUrl.regionMatches(false, 0, strArr[i], 0, strArr[i].length())) {
transformUrl = strArr[i] + transformUrl.substring(strArr[i].length());
}
if (z) {
return strArr[0] + transformUrl;
}
return transformUrl;
}
}
z = false;
if (z) {
return transformUrl;
}
return strArr[0] + transformUrl;
}
private static final void m25591a(ArrayList<LinkSpec> arrayList, Spannable spannable, Pattern pattern, String[] strArr, MatchFilter matchFilter, TransformFilter transformFilter) {
Matcher matcher = pattern.matcher(spannable);
while (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
if (matchFilter == null || matchFilter.acceptMatch(spannable, start, end)) {
LinkSpec linkSpec = new LinkSpec();
linkSpec.f17608a = m25587a(matcher.group(0), strArr, matcher, transformFilter);
linkSpec.f17609b = start;
linkSpec.f17610c = end;
arrayList.add(linkSpec);
}
}
}
private static final void m25590a(ArrayList<LinkSpec> arrayList, Spannable spannable) {
String obj = spannable.toString();
int i = 0;
while (true) {
String findAddress = WebView.findAddress(obj);
if (findAddress != null) {
int indexOf = obj.indexOf(findAddress);
if (indexOf >= 0) {
LinkSpec linkSpec = new LinkSpec();
int length = findAddress.length() + indexOf;
linkSpec.f17609b = indexOf + i;
linkSpec.f17610c = i + length;
obj = obj.substring(length);
i += length;
try {
linkSpec.f17608a = "geo:0,0?q=" + URLEncoder.encode(findAddress, "UTF-8");
arrayList.add(linkSpec);
} catch (UnsupportedEncodingException e) {
}
} else {
return;
}
}
return;
}
}
private static final void m25589a(ArrayList<LinkSpec> arrayList) {
Collections.sort(arrayList, new C12861());
int i = 0;
int size = arrayList.size();
while (i < size - 1) {
LinkSpec linkSpec = (LinkSpec) arrayList.get(i);
LinkSpec linkSpec2 = (LinkSpec) arrayList.get(i + 1);
if (linkSpec.f17609b <= linkSpec2.f17609b && linkSpec.f17610c > linkSpec2.f17609b) {
int i2;
if (linkSpec2.f17610c <= linkSpec.f17610c) {
i2 = i + 1;
} else if (linkSpec.f17610c - linkSpec.f17609b > linkSpec2.f17610c - linkSpec2.f17609b) {
i2 = i + 1;
} else if (linkSpec.f17610c - linkSpec.f17609b < linkSpec2.f17610c - linkSpec2.f17609b) {
i2 = i;
} else {
i2 = -1;
}
if (i2 != -1) {
arrayList.remove(i2);
size--;
}
}
i++;
}
}
}
| pxson001/facebook-app | classes6.dex_source_from_JADX/com/facebook/text/linkify/FbLinkify.java |
45,912 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedByteChannel;
import io.netty.util.internal.InternalLogger;
import io.netty.util.internal.InternalLoggerFactory;
import org.junit.Test;
import sun.net.util.IPAddressUtil;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksCmdType cmdType, SocksAddressType addressType, String host, int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host + " port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
EmbeddedByteChannel embedder = new EmbeddedByteChannel(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.addressType() == SocksAddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocksRequest);
} else {
msg = (SocksCmdRequest) embedder.readInbound();
assertSame(msg.cmdType(), cmdType);
assertSame(msg.addressType(), addressType);
assertEquals(msg.host(), host);
assertEquals(msg.port(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1",};
int[] ports = {0, 32769, 65535 };
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() {
String[] hosts = {SocksCommonUtils.ipv6toStr(IPAddressUtil.textToNumericFormatV6("::1"))};
int[] ports = {0, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {0, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (SocksCmdType cmdType : SocksCmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.UNKNOWN, host, port);
}
}
}
| ivanmemruk/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,913 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.handler.codec.socks;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.util.internal.SocketUtils;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.Test;
import java.net.UnknownHostException;
import static org.junit.Assert.*;
public class SocksCmdRequestDecoderTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocksCmdRequestDecoderTest.class);
private static void testSocksCmdRequestDecoderWithDifferentParams(SocksCmdType cmdType,
SocksAddressType addressType,
String host,
int port) {
logger.debug("Testing cmdType: " + cmdType + " addressType: " + addressType + " host: " + host +
" port: " + port);
SocksCmdRequest msg = new SocksCmdRequest(cmdType, addressType, host, port);
SocksCmdRequestDecoder decoder = new SocksCmdRequestDecoder();
EmbeddedChannel embedder = new EmbeddedChannel(decoder);
SocksCommonTestUtils.writeMessageIntoEmbedder(embedder, msg);
if (msg.addressType() == SocksAddressType.UNKNOWN) {
assertTrue(embedder.readInbound() instanceof UnknownSocksRequest);
} else {
msg = embedder.readInbound();
assertSame(msg.cmdType(), cmdType);
assertSame(msg.addressType(), addressType);
assertEquals(msg.host(), host);
assertEquals(msg.port(), port);
}
assertNull(embedder.readInbound());
}
@Test
public void testCmdRequestDecoderIPv4() {
String[] hosts = {"127.0.0.1", };
int[] ports = {1, 32769, 65535 };
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv4, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderIPv6() throws UnknownHostException {
String[] hosts = {SocksCommonUtils.ipv6toStr(SocketUtils.addressByName("::1").getAddress())};
int[] ports = {1, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.IPv6, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderDomain() {
String[] hosts = {"google.com" ,
"مثال.إختبار",
"παράδειγμα.δοκιμή",
"مثال.آزمایشی",
"пример.испытание",
"בײַשפּיל.טעסט",
"例子.测试",
"例子.測試",
"उदाहरण.परीक्षा",
"例え.テスト",
"실례.테스트",
"உதாரணம்.பரிட்சை"};
int[] ports = {1, 32769, 65535};
for (SocksCmdType cmdType : SocksCmdType.values()) {
for (String host : hosts) {
for (int port : ports) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.DOMAIN, host, port);
}
}
}
}
@Test
public void testCmdRequestDecoderUnknown() {
String host = "google.com";
int port = 80;
for (SocksCmdType cmdType : SocksCmdType.values()) {
testSocksCmdRequestDecoderWithDifferentParams(cmdType, SocksAddressType.UNKNOWN, host, port);
}
}
}
| benevans/netty | codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCmdRequestDecoderTest.java |
45,914 | package aQute.tester.junit.platform.test;
import static aQute.junit.constants.TesterConstants.TESTER_CONTINUOUS;
import static aQute.junit.constants.TesterConstants.TESTER_CONTROLPORT;
import static aQute.junit.constants.TesterConstants.TESTER_PORT;
import static aQute.junit.constants.TesterConstants.TESTER_UNRESOLVED;
import static aQute.tester.test.utils.TestRunData.nameOf;
import static org.eclipse.jdt.internal.junit.model.ITestRunListener2.STATUS_FAILURE;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.assertj.core.api.Assertions;
import org.junit.AssumptionViolatedException;
import org.junit.ComparisonFailure;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.JUnitException;
import org.opentest4j.AssertionFailedError;
import org.opentest4j.MultipleFailuresError;
import org.opentest4j.TestAbortedException;
import org.osgi.framework.Bundle;
import org.w3c.dom.Document;
import org.xmlunit.assertj.XmlAssert;
import aQute.launchpad.LaunchpadBuilder;
import aQute.lib.io.IO;
import aQute.tester.test.assertions.CustomAssertionError;
import aQute.tester.test.utils.ServiceLoaderMask;
import aQute.tester.test.utils.TestEntry;
import aQute.tester.test.utils.TestFailure;
import aQute.tester.test.utils.TestRunData;
import aQute.tester.test.utils.TestRunListener;
import aQute.tester.testbase.AbstractActivatorTest;
import aQute.tester.testclasses.JUnit3Test;
import aQute.tester.testclasses.JUnit4Test;
import aQute.tester.testclasses.With1Error1Failure;
import aQute.tester.testclasses.With2Failures;
import aQute.tester.testclasses.junit.platform.JUnit3ComparisonTest;
import aQute.tester.testclasses.junit.platform.JUnit4AbortTest;
import aQute.tester.testclasses.junit.platform.JUnit4ComparisonTest;
import aQute.tester.testclasses.junit.platform.JUnit4Skipper;
import aQute.tester.testclasses.junit.platform.JUnit5AbortTest;
import aQute.tester.testclasses.junit.platform.JUnit5ContainerSkipped;
import aQute.tester.testclasses.junit.platform.JUnit5ContainerSkippedWithCustomDisplayName;
import aQute.tester.testclasses.junit.platform.JUnit5DisplayNameTest;
import aQute.tester.testclasses.junit.platform.JUnit5ParameterizedTest;
import aQute.tester.testclasses.junit.platform.JUnit5SimpleComparisonTest;
import aQute.tester.testclasses.junit.platform.JUnit5Skipper;
import aQute.tester.testclasses.junit.platform.JUnit5Test;
import aQute.tester.testclasses.junit.platform.JUnitMixedComparisonTest;
import aQute.tester.testclasses.junit.platform.Mixed35Test;
import aQute.tester.testclasses.junit.platform.Mixed45Test;
public class ActivatorTest extends AbstractActivatorTest {
public ActivatorTest() {
super("aQute.tester.junit.platform.Activator", "biz.aQute.tester.junit-platform");
}
// We have the Jupiter engine on the classpath so that the tests will run.
// This classloader will hide it from the framework-under-test.
static final ClassLoader SERVICELOADER_MASK = new ServiceLoaderMask();
@Override
protected void createLP() {
builder.usingClassLoader(SERVICELOADER_MASK);
super.createLP();
}
@Test
public void multipleMixedTests_areAllRun_withJupiterTest() {
final ExitCode exitCode = runTests(JUnit3Test.class, JUnit4Test.class, JUnit5Test.class);
assertThat(exitCode.exitCode).as("exit code")
.isZero();
assertThat(testBundler.getCurrentThread(JUnit3Test.class)).as("junit3")
.isSameAs(Thread.currentThread());
assertThat(testBundler.getCurrentThread(JUnit4Test.class)).as("junit4")
.isSameAs(Thread.currentThread());
assertThat(testBundler.getCurrentThread(JUnit5Test.class)).as("junit5")
.isSameAs(Thread.currentThread());
}
@SuppressWarnings("unchecked")
@Test
public void multipleMixedTests_inASingleTestCase_areAllRun() {
final ExitCode exitCode = runTests(Mixed35Test.class, Mixed45Test.class);
assertThat(exitCode.exitCode).as("exit code")
.isZero();
assertThat(testBundler.getStatic(Mixed35Test.class, Set.class, "methods")).as("Mixed JUnit 3 & 5")
.containsExactlyInAnyOrder("testJUnit3", "junit5Test");
assertThat(testBundler.getStatic(Mixed45Test.class, Set.class, "methods")).as("Mixed JUnit 4 & 5")
.containsExactlyInAnyOrder("junit4Test", "junit5Test");
}
@Test
public void eclipseListener_reportsResults_acrossMultipleBundles() throws InterruptedException {
Class<?>[][] tests = {
{
With2Failures.class, JUnit4Test.class
}, {
With1Error1Failure.class, JUnit5Test.class
}
};
TestRunData result = runTestsEclipse(tests);
assertThat(result.getTestCount()).as("testCount")
.isEqualTo(9);
// @formatter:off
assertThat(result.getNameMap()
.keySet()).as("executed")
.contains(
nameOf(With2Failures.class),
nameOf(With2Failures.class, "test1"),
nameOf(With2Failures.class, "test2"),
nameOf(With2Failures.class, "test3"),
nameOf(JUnit4Test.class),
nameOf(JUnit4Test.class, "somethingElse"),
nameOf(With1Error1Failure.class),
nameOf(With1Error1Failure.class, "test1"),
nameOf(With1Error1Failure.class, "test2"),
nameOf(With1Error1Failure.class, "test3"),
nameOf(JUnit5Test.class, "somethingElseAgain"),
nameOf(testBundles.get(0)),
nameOf(testBundles.get(1))
);
assertThat(result).as("result")
.hasFailedTest(With2Failures.class, "test1", AssertionError.class)
.hasSuccessfulTest(With2Failures.class, "test2")
.hasFailedTest(With2Failures.class, "test3", CustomAssertionError.class)
.hasSuccessfulTest(JUnit4Test.class, "somethingElse")
.hasErroredTest(With1Error1Failure.class, "test1", RuntimeException.class)
.hasSuccessfulTest(With1Error1Failure.class, "test2")
.hasFailedTest(With1Error1Failure.class, "test3", AssertionError.class)
.hasSuccessfulTest(JUnit5Test.class, "somethingElseAgain")
;
// @formatter:on
}
private void readWithTimeout(InputStream inStr) throws Exception {
long endTime = System.currentTimeMillis() + 10000;
int available;
while ((available = inStr.available()) == 0 && System.currentTimeMillis() < endTime) {
Thread.sleep(10);
}
if (available == 0) {
Assertions.fail("Timeout waiting for data");
}
assertThat(available).as("control signal")
.isEqualTo(1);
int value = inStr.read();
assertThat(value).as("control value")
.isNotEqualTo(-1);
}
@Test
public void eclipseListener_worksInContinuousMode_withControlSocket() throws Exception {
try (ServerSocket controlSock = new ServerSocket(0)) {
controlSock.setSoTimeout(10000);
int controlPort = controlSock.getLocalPort();
builder.set("launch.services", "true")
.set(TESTER_CONTINUOUS, "true")
// This value should be ignored
.set(TESTER_PORT, Integer.toString(controlPort - 2))
.set(TESTER_CONTROLPORT, Integer.toString(controlPort));
createLP();
addTestBundle(With2Failures.class, JUnit4Test.class);
runTester();
try (Socket sock = controlSock.accept()) {
InputStream inStr = sock.getInputStream();
DataOutputStream outStr = new DataOutputStream(sock.getOutputStream());
readWithTimeout(inStr);
TestRunListener listener = startEclipseJUnitListener();
outStr.writeInt(eclipseJUnitPort);
outStr.flush();
listener.waitForClientToFinish(10000);
TestRunData result = listener.getLatestRunData();
if (result == null) {
fail("Result was null" + listener);
// To prevent NPE and allow any soft assertions to be
// displayed.
return;
}
assertThat(result.getTestCount()).as("testCount")
.isEqualTo(5);
// @formatter:off
assertThat(result.getNameMap()
.keySet()).as("executed")
.contains(
nameOf(With2Failures.class),
nameOf(With2Failures.class, "test1"),
nameOf(With2Failures.class, "test2"),
nameOf(With2Failures.class, "test3"),
nameOf(JUnit4Test.class),
nameOf(JUnit4Test.class, "somethingElse"),
nameOf(testBundles.get(0))
);
assertThat(result).as("result")
.hasFailedTest(With2Failures.class, "test1", AssertionError.class)
.hasSuccessfulTest(With2Failures.class, "test2")
.hasFailedTest(With2Failures.class, "test3", CustomAssertionError.class)
.hasSuccessfulTest(JUnit4Test.class, "somethingElse")
;
// @formatter:on
addTestBundle(With1Error1Failure.class, JUnit5Test.class);
readWithTimeout(inStr);
listener = startEclipseJUnitListener();
outStr.writeInt(eclipseJUnitPort);
outStr.flush();
listener.waitForClientToFinish(10000);
result = listener.getLatestRunData();
if (result == null) {
fail("Eclipse didn't capture output from the second run");
return;
}
int i = 2;
assertThat(result.getTestCount()).as("testCount:" + i)
.isEqualTo(4);
// @formatter:off
assertThat(result.getNameMap()
.keySet()).as("executed:2")
.contains(
nameOf(With1Error1Failure.class),
nameOf(With1Error1Failure.class, "test1"),
nameOf(With1Error1Failure.class, "test2"),
nameOf(With1Error1Failure.class, "test3"),
nameOf(JUnit5Test.class, "somethingElseAgain"),
nameOf(testBundles.get(1))
);
assertThat(result).as("result:2")
.hasErroredTest(With1Error1Failure.class, "test1", RuntimeException.class)
.hasSuccessfulTest(With1Error1Failure.class, "test2")
.hasFailedTest(With1Error1Failure.class, "test3", AssertionError.class)
.hasSuccessfulTest(JUnit5Test.class, "somethingElseAgain")
;
// @formatter:on
}
}
}
@Test
public void eclipseListener_reportsComparisonFailures() throws InterruptedException {
Class<?>[] tests = {
JUnit3ComparisonTest.class, JUnit4ComparisonTest.class, JUnit5SimpleComparisonTest.class, JUnit5Test.class,
JUnitMixedComparisonTest.class
};
TestRunData result = runTestsEclipse(tests);
final String[] order = {
"1", "2", "3.1", "3.2", "3.4", "4"
};
// @formatter:off
assertThat(result).as("result")
.hasFailedTest(JUnit3ComparisonTest.class, "testComparisonFailure", junit.framework.ComparisonFailure.class, "expected", "actual")
.hasFailedTest(JUnit4ComparisonTest.class, "comparisonFailure", ComparisonFailure.class, "expected", "actual")
.hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class, "expected", "actual")
.hasFailedTest(JUnitMixedComparisonTest.class, "multipleComparisonFailure", MultipleFailuresError.class,
Stream.of(order).map(x -> "expected" + x).collect(Collectors.joining("\n\n")),
Stream.of(order).map(x -> "actual" + x).collect(Collectors.joining("\n\n"))
)
;
// @formatter:on
TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure"));
assertThat(f).as("emptyComparisonFailure")
.isNotNull();
if (f != null) {
assertThat(f.status).as("emptyComparisonFailure:status")
.isEqualTo(STATUS_FAILURE);
assertThat(f.expected).as("emptyComparisonFailure:expected")
.isNull();
assertThat(f.actual).as("emptyComparisonFailure:actual")
.isNull();
}
}
@Test
public void eclipseListener_reportsParameterizedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5ParameterizedTest.class);
TestEntry methodTest = result.getTest(JUnit5ParameterizedTest.class, "parameterizedMethod");
if (methodTest == null) {
fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, "parameterizedMethod"));
return;
}
assertThat(methodTest.parameterTypes).as("parameterTypes")
.containsExactly("java.lang.String", "float");
List<TestEntry> parameterTests = result.getChildrenOf(methodTest.testId)
.stream()
.map(x -> result.getById(x))
.collect(Collectors.toList());
assertThat(parameterTests.stream()
.map(x -> x.testName)).as("testNames")
.allMatch(x -> x.equals(nameOf(JUnit5ParameterizedTest.class, "parameterizedMethod")));
assertThat(parameterTests.stream()).as("dynamic")
.allMatch(x -> x.isDynamicTest);
assertThat(parameterTests.stream()
.map(x -> x.displayName)).as("displayNames")
.containsExactlyInAnyOrder("1 ==> param: 'one', param2: 1.0", "2 ==> param: 'two', param2: 2.0",
"3 ==> param: 'three', param2: 3.0", "4 ==> param: 'four', param2: 4.0",
"5 ==> param: 'five', param2: 5.0");
Optional<TestEntry> test4 = parameterTests.stream()
.filter(x -> x.displayName.startsWith("4 ==>"))
.findFirst();
if (!test4.isPresent()) {
fail("Couldn't find test result for parameter 4");
} else {
assertThat(parameterTests.stream()
.filter(x -> result.getFailure(x.testId) != null)).as("failures")
.containsExactly(test4.get());
}
}
@Test
public void eclipseListener_reportsMisconfiguredParameterizedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5ParameterizedTest.class);
TestEntry methodTest = result.getTest(JUnit5ParameterizedTest.class, "misconfiguredMethod");
if (methodTest == null) {
fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, "misconfiguredMethod"));
return;
}
TestFailure failure = result.getFailure(methodTest.testId);
if (failure == null) {
fail("Expecting method:\n%s\nto have failed", methodTest);
} else {
assertThat(failure.trace).as("trace")
.startsWith("org.junit.platform.commons.JUnitException: Could not find method: unknownMethod");
}
}
@Test
public void eclipseListener_reportsCustomNames_withOddCharacters() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5DisplayNameTest.class);
final String[] methodList = {
"test1", "testWithNonASCII", "testWithNonLatin"
};
final String[] displayList = {
// "Test 1", "Prüfung 2", "Δοκιμή 3"
"Test 1", "Pr\u00fcfung 2", "\u0394\u03bf\u03ba\u03b9\u03bc\u03ae 3"
};
for (int i = 0; i < methodList.length; i++) {
final String method = methodList[i];
final String display = displayList[i];
TestEntry methodTest = result.getTest(JUnit5DisplayNameTest.class, method);
if (methodTest == null) {
fail("Couldn't find method test entry for " + nameOf(JUnit5ParameterizedTest.class, method));
continue;
}
assertThat(methodTest.displayName).as(String.format("[%d] %s", i, method))
.isEqualTo(display);
}
}
@Test
public void eclipseListener_reportsSkippedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5Skipper.class, JUnit5ContainerSkipped.class,
JUnit5ContainerSkippedWithCustomDisplayName.class, JUnit4Skipper.class);
assertThat(result).as("result")
.hasSkippedTest(JUnit5Skipper.class, "disabledTest", "with custom message")
.hasSkippedTest(JUnit5ContainerSkipped.class, "with another message")
.hasSkippedTest(JUnit5ContainerSkipped.class, "disabledTest2",
"ancestor \"JUnit5ContainerSkipped\" was skipped")
.hasSkippedTest(JUnit5ContainerSkipped.class, "disabledTest3",
"ancestor \"JUnit5ContainerSkipped\" was skipped")
.hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "with a third message")
.hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "disabledTest2",
"ancestor \"Skipper Class\" was skipped")
.hasSkippedTest(JUnit5ContainerSkippedWithCustomDisplayName.class, "disabledTest3",
"ancestor \"Skipper Class\" was skipped")
.hasSkippedTest(JUnit4Skipper.class, "disabledTest", "This is a test");
}
@Test
public void eclipseListener_reportsAbortedTests() throws InterruptedException {
TestRunData result = runTestsEclipse(JUnit5AbortTest.class, JUnit4AbortTest.class);
assertThat(result).as("result")
.hasAbortedTest(JUnit5AbortTest.class, "abortedTest",
new TestAbortedException("Assumption failed: I just can't go on"))
.hasAbortedTest(JUnit4AbortTest.class, "abortedTest",
new AssumptionViolatedException("Let's get outta here"));
}
@Test
public void eclipseListener_handlesNoEnginesGracefully() throws Exception {
try (LaunchpadBuilder builder = new LaunchpadBuilder()) {
IO.close(this.builder);
builder.bndrun("no-engines.bndrun")
.excludeExport("org.junit*")
.excludeExport("junit*");
this.builder = builder;
setTmpDir();
TestRunData result = runTestsEclipse(JUnit5AbortTest.class, JUnit4AbortTest.class);
assertThat(result).hasErroredTest("Initialization Error",
new JUnitException("Couldn't find any registered TestEngines"));
}
}
@Test
public void eclipseListener_handlesNoJUnit3Gracefully() throws Exception {
builder.excludeExport("junit.framework");
Class<?>[] tests = {
JUnit4ComparisonTest.class, JUnit5Test.class, JUnit5SimpleComparisonTest.class
};
TestRunData result = runTestsEclipse(tests);
assertThat(result).as("result")
.hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class,
"expected", "actual");
TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure"));
assertThat(f).as("emptyComparisonFailure")
.isNotNull();
if (f != null) {
assertThat(f.status).as("emptyComparisonFailure:status")
.isEqualTo(STATUS_FAILURE);
assertThat(f.expected).as("emptyComparisonFailure:expected")
.isNull();
assertThat(f.actual).as("emptyComparisonFailure:actual")
.isNull();
}
}
@Test
public void eclipseListener_handlesNoJUnit4Gracefully() throws Exception {
try (LaunchpadBuilder builder = new LaunchpadBuilder()) {
IO.close(this.builder);
builder.debug();
builder.bndrun("no-vintage-engine.bndrun")
.excludeExport("aQute.tester.bundle.*")
.excludeExport("org.junit*")
.excludeExport("junit*");
this.builder = builder;
setTmpDir();
Class<?>[] tests = {
JUnit3ComparisonTest.class, JUnit5Test.class, JUnit5SimpleComparisonTest.class
};
TestRunData result = runTestsEclipse(tests);
assertThat(result).as("result")
.hasFailedTest(JUnit5SimpleComparisonTest.class, "somethingElseThatFailed", AssertionFailedError.class,
"expected", "actual");
TestFailure f = result.getFailureByName(nameOf(JUnit5SimpleComparisonTest.class, "emptyComparisonFailure"));
assertThat(f).as("emptyComparisonFailure")
.isNotNull();
if (f != null) {
assertThat(f.status).as("emptyComparisonFailure:status")
.isEqualTo(STATUS_FAILURE);
assertThat(f.expected).as("emptyComparisonFailure:expected")
.isNull();
assertThat(f.actual).as("emptyComparisonFailure:actual")
.isNull();
}
}
}
@Test
public void testerUnresolvedTrue_isPassedThroughToBundleEngine() {
builder.set(TESTER_UNRESOLVED, "true");
AtomicReference<Bundle> bundleRef = new AtomicReference<>();
TestRunData result = runTestsEclipse(() -> {
bundleRef.set(bundle().importPackage("some.unknown.package")
.install());
}, JUnit3Test.class, JUnit4Test.class);
assertThat(result).hasSuccessfulTest("Unresolved bundles");
}
@Test
public void testerUnresolvedFalse_isPassedThroughToBundleEngine() {
builder.set(TESTER_UNRESOLVED, "false");
AtomicReference<Bundle> bundleRef = new AtomicReference<>();
TestRunData result = runTestsEclipse(() -> {
bundleRef.set(bundle().importPackage("some.unknown.package")
.install());
}, JUnit3Test.class, JUnit4Test.class);
assertThat(result.getNameMap()
.get("Unresolved bundles")).isNull();
}
@Test
public void xmlReporter_generatesCompleteXmlFile() throws Exception {
final ExitCode exitCode = runTests(JUnit3Test.class, With1Error1Failure.class, With2Failures.class);
final String fileName = "TEST-" + testBundle.getSymbolicName() + "-" + testBundle.getVersion() + ".xml";
File xmlFile = new File(getTmpDir(), fileName);
Assertions.assertThat(xmlFile)
.as("xmlFile")
.exists();
AtomicReference<Document> docContainer = new AtomicReference<>();
Assertions.assertThatCode(() -> {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
docContainer.set(dBuilder.parse(xmlFile));
})
.doesNotThrowAnyException();
Document doc = docContainer.get();
XmlAssert.assertThat(doc)
.nodesByXPath("/testsuite")
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testSuite() + "/testcase")
.hasSize(7);
XmlAssert.assertThat(doc)
.nodesByXPath(testCase(JUnit3Test.class, "testSomething"))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseError(With1Error1Failure.class, "test1", RuntimeException.class))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCase(With1Error1Failure.class, "test2"))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseFailure(With1Error1Failure.class, "test3", AssertionError.class))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseFailure(With2Failures.class, "test1", AssertionError.class))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCase(With2Failures.class, "test2"))
.hasSize(1);
XmlAssert.assertThat(doc)
.nodesByXPath(testCaseFailure(With2Failures.class, "test3", CustomAssertionError.class))
.hasSize(1);
}
}
| cdietrich/bnd | biz.aQute.tester.test/test/aQute/tester/junit/platform/test/ActivatorTest.java |