proj_name
stringclasses
157 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
49
masked_class
stringlengths
68
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
27
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
DeemOpen_zkui
zkui/src/main/java/com/deem/zkui/controller/Export.java
Export
doGet
class Export extends HttpServlet { private final static Logger logger = LoggerFactory.getLogger(Export.class); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>} }
logger.debug("Export Get Action!"); try { Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps"); String zkServer = globalProps.getProperty("zkServer"); String[] zkServerLst = zkServer.split(","); String authRole = (String) request.getSession().getAttribute("authRole"); if (authRole == null) { authRole = ZooKeeperUtil.ROLE_USER; } String zkPath = request.getParameter("zkPath"); StringBuilder output = new StringBuilder(); output.append("#App Config Dashboard (ACD) dump created on :").append(new Date()).append("\n"); Set<LeafBean> leaves = ZooKeeperUtil.INSTANCE.exportTree(zkPath, ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps), authRole); for (LeafBean leaf : leaves) { output.append(leaf.getPath()).append('=').append(leaf.getName()).append('=').append(ServletUtil.INSTANCE.externalizeNodeValue(leaf.getValue())).append('\n'); }// for all leaves response.setContentType("text/plain;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.write(output.toString()); } } catch (InterruptedException | KeeperException ex) { logger.error(Arrays.toString(ex.getStackTrace())); ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); }
72
407
479
<no_super_class>
DeemOpen_zkui
zkui/src/main/java/com/deem/zkui/controller/Import.java
Import
doPost
class Import extends HttpServlet { private final static Logger logger = LoggerFactory.getLogger(Import.class); @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>} }
logger.debug("Importing Action!"); try { Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps"); Dao dao = new Dao(globalProps); String zkServer = globalProps.getProperty("zkServer"); String[] zkServerLst = zkServer.split(","); StringBuilder sbFile = new StringBuilder(); String scmOverwrite = "false"; String scmServer = ""; String scmFilePath = ""; String scmFileRevision = ""; String uploadFileName = ""; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1034); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("scmOverwrite")) { scmOverwrite = item.getString(); } if (item.getFieldName().equals("scmServer")) { scmServer = item.getString(); } if (item.getFieldName().equals("scmFilePath")) { scmFilePath = item.getString(); } if (item.getFieldName().equals("scmFileRevision")) { scmFileRevision = item.getString(); } } else { uploadFileName = item.getName(); sbFile.append(item.getString("UTF-8")); } } InputStream inpStream; if (sbFile.toString().length() == 0) { uploadFileName = scmServer + scmFileRevision + "@" + scmFilePath; logger.debug("P4 file Processing " + uploadFileName); dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Importing P4 File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite); URL url = new URL(uploadFileName); URLConnection conn = url.openConnection(); inpStream = conn.getInputStream(); } else { logger.debug("Upload file Processing " + uploadFileName); dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Uploading File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite); inpStream = new ByteArrayInputStream(sbFile.toString().getBytes("UTF-8")); } // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(inpStream)); String inputLine; List<String> importFile = new ArrayList<>(); Integer lineCnt = 0; while ((inputLine = br.readLine()) != null) { lineCnt++; // Empty or comment? if (inputLine.trim().equals("") || inputLine.trim().startsWith("#")) { continue; } if (inputLine.startsWith("-")) { //DO nothing. } else if (!inputLine.matches("/.+=.+=.*")) { throw new IOException("Invalid format at line " + lineCnt + ": " + inputLine); } importFile.add(inputLine); } br.close(); ZooKeeperUtil.INSTANCE.importData(importFile, Boolean.valueOf(scmOverwrite), ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps)); for (String line : importFile) { if (line.startsWith("-")) { dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Deleting Entry: " + line); } else { dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Adding Entry: " + line); } } request.getSession().setAttribute("flashMsg", "Import Completed!"); response.sendRedirect("/home"); } catch (FileUploadException | IOException | InterruptedException | KeeperException ex) { logger.error(Arrays.toString(ex.getStackTrace())); ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); }
71
1,154
1,225
<no_super_class>
DeemOpen_zkui
zkui/src/main/java/com/deem/zkui/controller/Login.java
Login
doGet
class Login extends HttpServlet { private final static Logger logger = LoggerFactory.getLogger(Login.class); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>} @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Login Post Action!"); try { Properties globalProps = (Properties) getServletContext().getAttribute("globalProps"); Map<String, Object> templateParam = new HashMap<>(); HttpSession session = request.getSession(true); session.setMaxInactiveInterval(Integer.valueOf(globalProps.getProperty("sessionTimeout"))); //TODO: Implement custom authentication logic if required. String username = request.getParameter("username"); String password = request.getParameter("password"); String role = null; Boolean authenticated = false; //if ldap is provided then it overrides roleset. if (globalProps.getProperty("ldapAuth").equals("true")) { authenticated = new LdapAuth().authenticateUser(globalProps.getProperty("ldapUrl"), username, password, globalProps.getProperty("ldapDomain")); if (authenticated) { JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser().parse(globalProps.getProperty("ldapRoleSet"))).get("users"); for (Iterator it = jsonRoleSet.iterator(); it.hasNext();) { JSONObject jsonUser = (JSONObject) it.next(); if (jsonUser.get("username") != null && jsonUser.get("username").equals("*")) { role = (String) jsonUser.get("role"); } if (jsonUser.get("username") != null && jsonUser.get("username").equals(username)) { role = (String) jsonUser.get("role"); } } if (role == null) { role = ZooKeeperUtil.ROLE_USER; } } } else { JSONArray jsonRoleSet = (JSONArray) ((JSONObject) new JSONParser().parse(globalProps.getProperty("userSet"))).get("users"); for (Iterator it = jsonRoleSet.iterator(); it.hasNext();) { JSONObject jsonUser = (JSONObject) it.next(); if (jsonUser.get("username").equals(username) && jsonUser.get("password").equals(password)) { authenticated = true; role = (String) jsonUser.get("role"); } } } if (authenticated) { logger.info("Login successful: " + username); session.setAttribute("authName", username); session.setAttribute("authRole", role); response.sendRedirect("/home"); } else { session.setAttribute("flashMsg", "Invalid Login"); ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "login.ftl.html"); } } catch (ParseException | TemplateException ex) { logger.error(Arrays.toString(ex.getStackTrace())); ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); } } }
logger.debug("Login Action!"); try { Properties globalProps = (Properties) getServletContext().getAttribute("globalProps"); Map<String, Object> templateParam = new HashMap<>(); templateParam.put("uptime", globalProps.getProperty("uptime")); templateParam.put("loginMessage", globalProps.getProperty("loginMessage")); ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "login.ftl.html"); } catch (TemplateException ex) { logger.error(Arrays.toString(ex.getStackTrace())); ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); }
817
168
985
<no_super_class>
DeemOpen_zkui
zkui/src/main/java/com/deem/zkui/controller/Logout.java
Logout
doGet
class Logout extends HttpServlet { private final static Logger logger = LoggerFactory.getLogger(Logout.class); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>} }
try { logger.debug("Logout Action!"); Properties globalProps = (Properties) getServletContext().getAttribute("globalProps"); String zkServer = globalProps.getProperty("zkServer"); String[] zkServerLst = zkServer.split(","); ZooKeeper zk = ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0],globalProps); request.getSession().invalidate(); zk.close(); response.sendRedirect("/login"); } catch (InterruptedException ex) { logger.error(Arrays.toString(ex.getStackTrace())); ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); }
73
189
262
<no_super_class>
DeemOpen_zkui
zkui/src/main/java/com/deem/zkui/controller/Monitor.java
Monitor
doGet
class Monitor extends HttpServlet { private final static Logger logger = LoggerFactory.getLogger(Monitor.class); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>} }
logger.debug("Monitor Action!"); try { Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps"); String zkServer = globalProps.getProperty("zkServer"); String[] zkServerLst = zkServer.split(","); Map<String, Object> templateParam = new HashMap<>(); StringBuffer stats = new StringBuffer(); for (String zkObj : zkServerLst) { stats.append("<br/><hr/><br/>").append("Server: ").append(zkObj).append("<br/><hr/><br/>"); String[] monitorZKServer = zkObj.split(":"); stats.append(CmdUtil.INSTANCE.executeCmd("stat", monitorZKServer[0], monitorZKServer[1])); stats.append(CmdUtil.INSTANCE.executeCmd("envi", monitorZKServer[0], monitorZKServer[1])); } templateParam.put("stats", stats); ServletUtil.INSTANCE.renderHtml(request, response, templateParam, "monitor.ftl.html"); } catch (IOException | TemplateException ex) { logger.error(Arrays.toString(ex.getStackTrace())); ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); }
71
334
405
<no_super_class>
DeemOpen_zkui
zkui/src/main/java/com/deem/zkui/controller/RestAccess.java
RestAccess
doGet
class RestAccess extends HttpServlet { private final static Logger logger = LoggerFactory.getLogger(RestAccess.class); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<FILL_FUNCTION_BODY>} }
logger.debug("Rest Action!"); ZooKeeper zk = null; try { Properties globalProps = (Properties) this.getServletContext().getAttribute("globalProps"); String zkServer = globalProps.getProperty("zkServer"); String[] zkServerLst = zkServer.split(","); String accessRole = ZooKeeperUtil.ROLE_USER; if ((globalProps.getProperty("blockPwdOverRest") != null) && (Boolean.valueOf(globalProps.getProperty("blockPwdOverRest")) == Boolean.FALSE)) { accessRole = ZooKeeperUtil.ROLE_ADMIN; } StringBuilder resultOut = new StringBuilder(); String clusterName = request.getParameter("cluster"); String appName = request.getParameter("app"); String hostName = request.getParameter("host"); String[] propNames = request.getParameterValues("propNames"); String propValue = ""; LeafBean propertyNode; if (hostName == null) { hostName = ServletUtil.INSTANCE.getRemoteAddr(request); } zk = ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps); //get the path of the hosts entry. LeafBean hostsNode = null; //If app name is mentioned then lookup path is appended with it. if (appName != null && ZooKeeperUtil.INSTANCE.nodeExists(ZooKeeperUtil.ZK_HOSTS + "/" + hostName + ":" + appName, zk)) { hostsNode = ZooKeeperUtil.INSTANCE.getNodeValue(zk, ZooKeeperUtil.ZK_HOSTS, ZooKeeperUtil.ZK_HOSTS + "/" + hostName + ":" + appName, hostName + ":" + appName, accessRole); } else { hostsNode = ZooKeeperUtil.INSTANCE.getNodeValue(zk, ZooKeeperUtil.ZK_HOSTS, ZooKeeperUtil.ZK_HOSTS + "/" + hostName, hostName, accessRole); } String lookupPath = hostsNode.getStrValue(); logger.trace("Root Path:" + lookupPath); String[] pathElements = lookupPath.split("/"); //Form all combinations of search path you want to look up the property in. List<String> searchPath = new ArrayList<>(); StringBuilder pathSubSet = new StringBuilder(); for (String pathElement : pathElements) { pathSubSet.append(pathElement); pathSubSet.append("/"); searchPath.add(pathSubSet.substring(0, pathSubSet.length() - 1)); } //You specify a cluster or an app name to group. if (clusterName != null && appName == null) { if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + hostName, zk)) { searchPath.add(lookupPath + "/" + hostName); } if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName, zk)) { searchPath.add(lookupPath + "/" + clusterName); } if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName + "/" + hostName, zk)) { searchPath.add(lookupPath + "/" + clusterName + "/" + hostName); } } else if (appName != null && clusterName == null) { if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + hostName, zk)) { searchPath.add(lookupPath + "/" + hostName); } if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + appName, zk)) { searchPath.add(lookupPath + "/" + appName); } if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + appName + "/" + hostName, zk)) { searchPath.add(lookupPath + "/" + appName + "/" + hostName); } } else if (appName != null && clusterName != null) { //Order in which these paths are listed is important as the lookup happens in that order. //Precedence is give to cluster over app. if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + hostName, zk)) { searchPath.add(lookupPath + "/" + hostName); } if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + appName, zk)) { searchPath.add(lookupPath + "/" + appName); } if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + appName + "/" + hostName, zk)) { searchPath.add(lookupPath + "/" + appName + "/" + hostName); } if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName, zk)) { searchPath.add(lookupPath + "/" + clusterName); } if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName + "/" + hostName, zk)) { searchPath.add(lookupPath + "/" + clusterName + "/" + hostName); } if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName + "/" + appName, zk)) { searchPath.add(lookupPath + "/" + clusterName + "/" + appName); } if (ZooKeeperUtil.INSTANCE.nodeExists(lookupPath + "/" + clusterName + "/" + appName + "/" + hostName, zk)) { searchPath.add(lookupPath + "/" + clusterName + "/" + appName + "/" + hostName); } } //Search the property in all lookup paths. for (String propName : propNames) { propValue = null; for (String path : searchPath) { logger.trace("Looking up " + path); propertyNode = ZooKeeperUtil.INSTANCE.getNodeValue(zk, path, path + "/" + propName, propName, accessRole); if (propertyNode != null) { propValue = propertyNode.getStrValue(); } } if (propValue != null) { resultOut.append(propName).append("=").append(propValue).append("\n"); } } response.setContentType("text/plain;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.write(resultOut.toString()); } } catch (KeeperException | InterruptedException ex) { logger.error(Arrays.toString(ex.getStackTrace())); ServletUtil.INSTANCE.renderError(request, response, ex.getMessage()); } finally { if (zk != null) { ServletUtil.INSTANCE.closeZookeeper(zk); } }
73
1,856
1,929
<no_super_class>
DeemOpen_zkui
zkui/src/main/java/com/deem/zkui/dao/Dao.java
Dao
checkNCreate
class Dao { private final static Integer FETCH_LIMIT = 50; private final static org.slf4j.Logger logger = LoggerFactory.getLogger(Dao.class); private final Properties globalProps; public Dao(Properties globalProps) { this.globalProps = globalProps; } public void open() { Base.open(globalProps.getProperty("jdbcClass"), globalProps.getProperty("jdbcUrl"), globalProps.getProperty("jdbcUser"), globalProps.getProperty("jdbcPwd")); } public void close() { Base.close(); } public void checkNCreate() {<FILL_FUNCTION_BODY>} public List<History> fetchHistoryRecords() { this.open(); List<History> history = History.findAll().orderBy("ID desc").limit(FETCH_LIMIT); history.size(); this.close(); return history; } public List<History> fetchHistoryRecordsByNode(String historyNode) { this.open(); List<History> history = History.where("CHANGE_SUMMARY like ?", historyNode).orderBy("ID desc").limit(FETCH_LIMIT); history.size(); this.close(); return history; } public void insertHistory(String user, String ipAddress, String summary) { try { this.open(); //To avoid errors due to truncation. if (summary.length() >= 500) { summary = summary.substring(0, 500); } History history = new History(); history.setChangeUser(user); history.setChangeIp(ipAddress); history.setChangeSummary(summary); history.setChangeDate(new Date()); history.save(); this.close(); } catch (Exception ex) { logger.error(Arrays.toString(ex.getStackTrace())); } } }
try { Flyway flyway = new Flyway(); flyway.setDataSource(globalProps.getProperty("jdbcUrl"), globalProps.getProperty("jdbcUser"), globalProps.getProperty("jdbcPwd")); //Will wipe db each time. Avoid this in prod. if (globalProps.getProperty("env").equals("dev")) { flyway.clean(); } //Remove the above line if deploying to prod. flyway.migrate(); } catch (Exception ex) { logger.error("Error trying to migrate db! Not severe hence proceeding forward."); }
511
156
667
<no_super_class>
DeemOpen_zkui
zkui/src/main/java/com/deem/zkui/filter/AuthFilter.java
AuthFilter
doFilter
class AuthFilter implements Filter { @Override public void init(FilterConfig fc) throws ServletException { //Do Nothing } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {<FILL_FUNCTION_BODY>} @Override public void destroy() { //Do nothing } }
HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (!request.getRequestURI().contains("/login") && !request.getRequestURI().contains("/acd/appconfig")) { RequestDispatcher dispatcher; HttpSession session = request.getSession(); if (session != null) { if (session.getAttribute("authName") == null || session.getAttribute("authRole") == null) { response.sendRedirect("/login"); return; } } else { request.setAttribute("fail_msg", "Session timed out!"); dispatcher = request.getRequestDispatcher("/Login"); dispatcher.forward(request, response); return; } } fc.doFilter(req, res);
104
208
312
<no_super_class>
DeemOpen_zkui
zkui/src/main/java/com/deem/zkui/listener/SessionListener.java
SessionListener
sessionDestroyed
class SessionListener implements HttpSessionListener { private static final Logger logger = LoggerFactory.getLogger(SessionListener.class); @Override public void sessionCreated(HttpSessionEvent event) { logger.trace("Session created"); } @Override public void sessionDestroyed(HttpSessionEvent event) {<FILL_FUNCTION_BODY>} }
try { ZooKeeper zk = (ZooKeeper) event.getSession().getAttribute("zk"); zk.close(); logger.trace("Session destroyed"); } catch (InterruptedException ex) { logger.error(Arrays.toString(ex.getStackTrace())); }
96
82
178
<no_super_class>
DeemOpen_zkui
zkui/src/main/java/com/deem/zkui/utils/LdapAuth.java
LdapAuth
authenticateUser
class LdapAuth { DirContext ctx = null; private final static org.slf4j.Logger logger = LoggerFactory.getLogger(LdapAuth.class); public boolean authenticateUser(String ldapUrl, String username, String password, String domains) {<FILL_FUNCTION_BODY>} }
String[] domainArr = domains.split(","); for (String domain : domainArr) { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, domain + "\\" + username); env.put(Context.SECURITY_CREDENTIALS, password); try { ctx = new InitialDirContext(env); return true; } catch (NamingException e) { } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException ex) { logger.warn(ex.getMessage()); } } } } return false;
84
261
345
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/BinaryBitmap.java
BinaryBitmap
getBlackMatrix
class BinaryBitmap { private final Binarizer binarizer; private BitMatrix matrix; public BinaryBitmap(Binarizer binarizer) { if (binarizer == null) { throw new IllegalArgumentException("Binarizer must be non-null."); } this.binarizer = binarizer; } /** * @return The width of the bitmap. */ public int getWidth() { return binarizer.getWidth(); } /** * @return The height of the bitmap. */ public int getHeight() { return binarizer.getHeight(); } /** * Converts one row of luminance data to 1 bit data. May actually do the conversion, or return * cached data. Callers should assume this method is expensive and call it as seldom as possible. * This method is intended for decoding 1D barcodes and may choose to apply sharpening. * * @param y The row to fetch, which must be in [0, bitmap height) * @param row An optional preallocated array. If null or too small, it will be ignored. * If used, the Binarizer will call BitArray.clear(). Always use the returned object. * @return The array of bits for this row (true means black). * @throws NotFoundException if row can't be binarized */ public BitArray getBlackRow(int y, BitArray row) throws NotFoundException { return binarizer.getBlackRow(y, row); } /** * Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive * and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or * may not apply sharpening. Therefore, a row from this matrix may not be identical to one * fetched using getBlackRow(), so don't mix and match between them. * * @return The 2D array of bits for the image (true means black). * @throws NotFoundException if image can't be binarized to make a matrix */ public BitMatrix getBlackMatrix() throws NotFoundException {<FILL_FUNCTION_BODY>} /** * @return Whether this bitmap can be cropped. */ public boolean isCropSupported() { return binarizer.getLuminanceSource().isCropSupported(); } /** * Returns a new object with cropped image data. Implementations may keep a reference to the * original data rather than a copy. Only callable if isCropSupported() is true. * * @param left The left coordinate, which must be in [0,getWidth()) * @param top The top coordinate, which must be in [0,getHeight()) * @param width The width of the rectangle to crop. * @param height The height of the rectangle to crop. * @return A cropped version of this object. */ public BinaryBitmap crop(int left, int top, int width, int height) { LuminanceSource newSource = binarizer.getLuminanceSource().crop(left, top, width, height); return new BinaryBitmap(binarizer.createBinarizer(newSource)); } /** * @return Whether this bitmap supports counter-clockwise rotation. */ public boolean isRotateSupported() { return binarizer.getLuminanceSource().isRotateSupported(); } /** * Returns a new object with rotated image data by 90 degrees counterclockwise. * Only callable if {@link #isRotateSupported()} is true. * * @return A rotated version of this object. */ public BinaryBitmap rotateCounterClockwise() { LuminanceSource newSource = binarizer.getLuminanceSource().rotateCounterClockwise(); return new BinaryBitmap(binarizer.createBinarizer(newSource)); } /** * Returns a new object with rotated image data by 45 degrees counterclockwise. * Only callable if {@link #isRotateSupported()} is true. * * @return A rotated version of this object. */ public BinaryBitmap rotateCounterClockwise45() { LuminanceSource newSource = binarizer.getLuminanceSource().rotateCounterClockwise45(); return new BinaryBitmap(binarizer.createBinarizer(newSource)); } @Override public String toString() { try { return getBlackMatrix().toString(); } catch (NotFoundException e) { return ""; } } }
// The matrix is created on demand the first time it is requested, then cached. There are two // reasons for this: // 1. This work will never be done if the caller only installs 1D Reader objects, or if a // 1D Reader finds a barcode before the 2D Readers run. // 2. This work will only be done once even if the caller installs multiple 2D Readers. if (matrix == null) { matrix = binarizer.getBlackMatrix(); } return matrix;
1,199
137
1,336
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/Dimension.java
Dimension
equals
class Dimension { private final int width; private final int height; public Dimension(int width, int height) { if (width < 0 || height < 0) { throw new IllegalArgumentException(); } this.width = width; this.height = height; } public int getWidth() { return width; } public int getHeight() { return height; } @Override public boolean equals(Object other) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return width * 32713 + height; } @Override public String toString() { return width + "x" + height; } }
if (other instanceof Dimension) { Dimension d = (Dimension) other; return width == d.width && height == d.height; } return false;
197
48
245
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/InvertedLuminanceSource.java
InvertedLuminanceSource
getMatrix
class InvertedLuminanceSource extends LuminanceSource { private final LuminanceSource delegate; public InvertedLuminanceSource(LuminanceSource delegate) { super(delegate.getWidth(), delegate.getHeight()); this.delegate = delegate; } @Override public byte[] getRow(int y, byte[] row) { row = delegate.getRow(y, row); int width = getWidth(); for (int i = 0; i < width; i++) { row[i] = (byte) (255 - (row[i] & 0xFF)); } return row; } @Override public byte[] getMatrix() {<FILL_FUNCTION_BODY>} @Override public boolean isCropSupported() { return delegate.isCropSupported(); } @Override public LuminanceSource crop(int left, int top, int width, int height) { return new InvertedLuminanceSource(delegate.crop(left, top, width, height)); } @Override public boolean isRotateSupported() { return delegate.isRotateSupported(); } /** * @return original delegate {@link LuminanceSource} since invert undoes itself */ @Override public LuminanceSource invert() { return delegate; } @Override public LuminanceSource rotateCounterClockwise() { return new InvertedLuminanceSource(delegate.rotateCounterClockwise()); } @Override public LuminanceSource rotateCounterClockwise45() { return new InvertedLuminanceSource(delegate.rotateCounterClockwise45()); } }
byte[] matrix = delegate.getMatrix(); int length = getWidth() * getHeight(); byte[] invertedMatrix = new byte[length]; for (int i = 0; i < length; i++) { invertedMatrix[i] = (byte) (255 - (matrix[i] & 0xFF)); } return invertedMatrix;
453
94
547
<methods>public com.google.zxing.LuminanceSource crop(int, int, int, int) ,public final int getHeight() ,public abstract byte[] getMatrix() ,public abstract byte[] getRow(int, byte[]) ,public final int getWidth() ,public com.google.zxing.LuminanceSource invert() ,public boolean isCropSupported() ,public boolean isRotateSupported() ,public com.google.zxing.LuminanceSource rotateCounterClockwise() ,public com.google.zxing.LuminanceSource rotateCounterClockwise45() ,public final java.lang.String toString() <variables>private final non-sealed int height,private final non-sealed int width
zxing_zxing
zxing/core/src/main/java/com/google/zxing/LuminanceSource.java
LuminanceSource
toString
class LuminanceSource { private final int width; private final int height; protected LuminanceSource(int width, int height) { this.width = width; this.height = height; } /** * Fetches one row of luminance data from the underlying platform's bitmap. Values range from * 0 (black) to 255 (white). Because Java does not have an unsigned byte type, callers will have * to bitwise and with 0xff for each value. It is preferable for implementations of this method * to only fetch this row rather than the whole image, since no 2D Readers may be installed and * getMatrix() may never be called. * * @param y The row to fetch, which must be in [0,getHeight()) * @param row An optional preallocated array. If null or too small, it will be ignored. * Always use the returned object, and ignore the .length of the array. * @return An array containing the luminance data. */ public abstract byte[] getRow(int y, byte[] row); /** * Fetches luminance data for the underlying bitmap. Values should be fetched using: * {@code int luminance = array[y * width + x] & 0xff} * * @return A row-major 2D array of luminance values. Do not use result.length as it may be * larger than width * height bytes on some platforms. Do not modify the contents * of the result. */ public abstract byte[] getMatrix(); /** * @return The width of the bitmap. */ public final int getWidth() { return width; } /** * @return The height of the bitmap. */ public final int getHeight() { return height; } /** * @return Whether this subclass supports cropping. */ public boolean isCropSupported() { return false; } /** * Returns a new object with cropped image data. Implementations may keep a reference to the * original data rather than a copy. Only callable if isCropSupported() is true. * * @param left The left coordinate, which must be in [0,getWidth()) * @param top The top coordinate, which must be in [0,getHeight()) * @param width The width of the rectangle to crop. * @param height The height of the rectangle to crop. * @return A cropped version of this object. */ public LuminanceSource crop(int left, int top, int width, int height) { throw new UnsupportedOperationException("This luminance source does not support cropping."); } /** * @return Whether this subclass supports counter-clockwise rotation. */ public boolean isRotateSupported() { return false; } /** * @return a wrapper of this {@code LuminanceSource} which inverts the luminances it returns -- black becomes * white and vice versa, and each value becomes (255-value). */ public LuminanceSource invert() { return new InvertedLuminanceSource(this); } /** * Returns a new object with rotated image data by 90 degrees counterclockwise. * Only callable if {@link #isRotateSupported()} is true. * * @return A rotated version of this object. */ public LuminanceSource rotateCounterClockwise() { throw new UnsupportedOperationException("This luminance source does not support rotation by 90 degrees."); } /** * Returns a new object with rotated image data by 45 degrees counterclockwise. * Only callable if {@link #isRotateSupported()} is true. * * @return A rotated version of this object. */ public LuminanceSource rotateCounterClockwise45() { throw new UnsupportedOperationException("This luminance source does not support rotation by 45 degrees."); } @Override public final String toString() {<FILL_FUNCTION_BODY>} }
byte[] row = new byte[width]; StringBuilder result = new StringBuilder(height * (width + 1)); for (int y = 0; y < height; y++) { row = getRow(y, row); for (int x = 0; x < width; x++) { int luminance = row[x] & 0xFF; char c; if (luminance < 0x40) { c = '#'; } else if (luminance < 0x80) { c = '+'; } else if (luminance < 0xC0) { c = '.'; } else { c = ' '; } result.append(c); } result.append('\n'); } return result.toString();
1,051
207
1,258
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/MultiFormatReader.java
MultiFormatReader
reset
class MultiFormatReader implements Reader { private static final Reader[] EMPTY_READER_ARRAY = new Reader[0]; private Map<DecodeHintType,?> hints; private Reader[] readers; /** * This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it * passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly. * Use setHints() followed by decodeWithState() for continuous scan applications. * * @param image The pixel data to decode * @return The contents of the image * @throws NotFoundException Any errors which occurred */ @Override public Result decode(BinaryBitmap image) throws NotFoundException { setHints(null); return decodeInternal(image); } /** * Decode an image using the hints provided. Does not honor existing state. * * @param image The pixel data to decode * @param hints The hints to use, clearing the previous state. * @return The contents of the image * @throws NotFoundException Any errors which occurred */ @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException { setHints(hints); return decodeInternal(image); } /** * Decode an image using the state set up by calling setHints() previously. Continuous scan * clients will get a <b>large</b> speed increase by using this instead of decode(). * * @param image The pixel data to decode * @return The contents of the image * @throws NotFoundException Any errors which occurred */ public Result decodeWithState(BinaryBitmap image) throws NotFoundException { // Make sure to set up the default state so we don't crash if (readers == null) { setHints(null); } return decodeInternal(image); } /** * This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls * to decodeWithState(image) can reuse the same set of readers without reallocating memory. This * is important for performance in continuous scan clients. * * @param hints The set of hints to use for subsequent calls to decode(image) */ public void setHints(Map<DecodeHintType,?> hints) { this.hints = hints; boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER); @SuppressWarnings("unchecked") Collection<BarcodeFormat> formats = hints == null ? null : (Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS); Collection<Reader> readers = new ArrayList<>(); if (formats != null) { boolean addOneDReader = formats.contains(BarcodeFormat.UPC_A) || formats.contains(BarcodeFormat.UPC_E) || formats.contains(BarcodeFormat.EAN_13) || formats.contains(BarcodeFormat.EAN_8) || formats.contains(BarcodeFormat.CODABAR) || formats.contains(BarcodeFormat.CODE_39) || formats.contains(BarcodeFormat.CODE_93) || formats.contains(BarcodeFormat.CODE_128) || formats.contains(BarcodeFormat.ITF) || formats.contains(BarcodeFormat.RSS_14) || formats.contains(BarcodeFormat.RSS_EXPANDED); // Put 1D readers upfront in "normal" mode if (addOneDReader && !tryHarder) { readers.add(new MultiFormatOneDReader(hints)); } if (formats.contains(BarcodeFormat.QR_CODE)) { readers.add(new QRCodeReader()); } if (formats.contains(BarcodeFormat.DATA_MATRIX)) { readers.add(new DataMatrixReader()); } if (formats.contains(BarcodeFormat.AZTEC)) { readers.add(new AztecReader()); } if (formats.contains(BarcodeFormat.PDF_417)) { readers.add(new PDF417Reader()); } if (formats.contains(BarcodeFormat.MAXICODE)) { readers.add(new MaxiCodeReader()); } // At end in "try harder" mode if (addOneDReader && tryHarder) { readers.add(new MultiFormatOneDReader(hints)); } } if (readers.isEmpty()) { if (!tryHarder) { readers.add(new MultiFormatOneDReader(hints)); } readers.add(new QRCodeReader()); readers.add(new DataMatrixReader()); readers.add(new AztecReader()); readers.add(new PDF417Reader()); readers.add(new MaxiCodeReader()); if (tryHarder) { readers.add(new MultiFormatOneDReader(hints)); } } this.readers = readers.toArray(EMPTY_READER_ARRAY); } @Override public void reset() {<FILL_FUNCTION_BODY>} private Result decodeInternal(BinaryBitmap image) throws NotFoundException { if (readers != null) { for (Reader reader : readers) { if (Thread.currentThread().isInterrupted()) { throw NotFoundException.getNotFoundInstance(); } try { return reader.decode(image, hints); } catch (ReaderException re) { // continue } } if (hints != null && hints.containsKey(DecodeHintType.ALSO_INVERTED)) { // Calling all readers again with inverted image image.getBlackMatrix().flip(); for (Reader reader : readers) { if (Thread.currentThread().isInterrupted()) { throw NotFoundException.getNotFoundInstance(); } try { return reader.decode(image, hints); } catch (ReaderException re) { // continue } } } } throw NotFoundException.getNotFoundInstance(); } }
if (readers != null) { for (Reader reader : readers) { reader.reset(); } }
1,636
36
1,672
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/MultiFormatWriter.java
MultiFormatWriter
encode
class MultiFormatWriter implements Writer { @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) throws WriterException {<FILL_FUNCTION_BODY>} }
Writer writer; switch (format) { case EAN_8: writer = new EAN8Writer(); break; case UPC_E: writer = new UPCEWriter(); break; case EAN_13: writer = new EAN13Writer(); break; case UPC_A: writer = new UPCAWriter(); break; case QR_CODE: writer = new QRCodeWriter(); break; case CODE_39: writer = new Code39Writer(); break; case CODE_93: writer = new Code93Writer(); break; case CODE_128: writer = new Code128Writer(); break; case ITF: writer = new ITFWriter(); break; case PDF_417: writer = new PDF417Writer(); break; case CODABAR: writer = new CodaBarWriter(); break; case DATA_MATRIX: writer = new DataMatrixWriter(); break; case AZTEC: writer = new AztecWriter(); break; default: throw new IllegalArgumentException("No encoder available for format " + format); } return writer.encode(contents, format, width, height, hints);
130
350
480
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/PlanarYUVLuminanceSource.java
PlanarYUVLuminanceSource
renderThumbnail
class PlanarYUVLuminanceSource extends LuminanceSource { private static final int THUMBNAIL_SCALE_FACTOR = 2; private final byte[] yuvData; private final int dataWidth; private final int dataHeight; private final int left; private final int top; public PlanarYUVLuminanceSource(byte[] yuvData, int dataWidth, int dataHeight, int left, int top, int width, int height, boolean reverseHorizontal) { super(width, height); if (left + width > dataWidth || top + height > dataHeight) { throw new IllegalArgumentException("Crop rectangle does not fit within image data."); } this.yuvData = yuvData; this.dataWidth = dataWidth; this.dataHeight = dataHeight; this.left = left; this.top = top; if (reverseHorizontal) { reverseHorizontal(width, height); } } @Override public byte[] getRow(int y, byte[] row) { if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Requested row is outside the image: " + y); } int width = getWidth(); if (row == null || row.length < width) { row = new byte[width]; } int offset = (y + top) * dataWidth + left; System.arraycopy(yuvData, offset, row, 0, width); return row; } @Override public byte[] getMatrix() { int width = getWidth(); int height = getHeight(); // If the caller asks for the entire underlying image, save the copy and give them the // original data. The docs specifically warn that result.length must be ignored. if (width == dataWidth && height == dataHeight) { return yuvData; } int area = width * height; byte[] matrix = new byte[area]; int inputOffset = top * dataWidth + left; // If the width matches the full width of the underlying data, perform a single copy. if (width == dataWidth) { System.arraycopy(yuvData, inputOffset, matrix, 0, area); return matrix; } // Otherwise copy one cropped row at a time. for (int y = 0; y < height; y++) { int outputOffset = y * width; System.arraycopy(yuvData, inputOffset, matrix, outputOffset, width); inputOffset += dataWidth; } return matrix; } @Override public boolean isCropSupported() { return true; } @Override public LuminanceSource crop(int left, int top, int width, int height) { return new PlanarYUVLuminanceSource(yuvData, dataWidth, dataHeight, this.left + left, this.top + top, width, height, false); } public int[] renderThumbnail() {<FILL_FUNCTION_BODY>} /** * @return width of image from {@link #renderThumbnail()} */ public int getThumbnailWidth() { return getWidth() / THUMBNAIL_SCALE_FACTOR; } /** * @return height of image from {@link #renderThumbnail()} */ public int getThumbnailHeight() { return getHeight() / THUMBNAIL_SCALE_FACTOR; } private void reverseHorizontal(int width, int height) { byte[] yuvData = this.yuvData; for (int y = 0, rowStart = top * dataWidth + left; y < height; y++, rowStart += dataWidth) { int middle = rowStart + width / 2; for (int x1 = rowStart, x2 = rowStart + width - 1; x1 < middle; x1++, x2--) { byte temp = yuvData[x1]; yuvData[x1] = yuvData[x2]; yuvData[x2] = temp; } } } }
int width = getWidth() / THUMBNAIL_SCALE_FACTOR; int height = getHeight() / THUMBNAIL_SCALE_FACTOR; int[] pixels = new int[width * height]; byte[] yuv = yuvData; int inputOffset = top * dataWidth + left; for (int y = 0; y < height; y++) { int outputOffset = y * width; for (int x = 0; x < width; x++) { int grey = yuv[inputOffset + x * THUMBNAIL_SCALE_FACTOR] & 0xff; pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101); } inputOffset += dataWidth * THUMBNAIL_SCALE_FACTOR; } return pixels;
1,087
233
1,320
<methods>public com.google.zxing.LuminanceSource crop(int, int, int, int) ,public final int getHeight() ,public abstract byte[] getMatrix() ,public abstract byte[] getRow(int, byte[]) ,public final int getWidth() ,public com.google.zxing.LuminanceSource invert() ,public boolean isCropSupported() ,public boolean isRotateSupported() ,public com.google.zxing.LuminanceSource rotateCounterClockwise() ,public com.google.zxing.LuminanceSource rotateCounterClockwise45() ,public final java.lang.String toString() <variables>private final non-sealed int height,private final non-sealed int width
zxing_zxing
zxing/core/src/main/java/com/google/zxing/RGBLuminanceSource.java
RGBLuminanceSource
getMatrix
class RGBLuminanceSource extends LuminanceSource { private final byte[] luminances; private final int dataWidth; private final int dataHeight; private final int left; private final int top; public RGBLuminanceSource(int width, int height, int[] pixels) { super(width, height); dataWidth = width; dataHeight = height; left = 0; top = 0; // In order to measure pure decoding speed, we convert the entire image to a greyscale array // up front, which is the same as the Y channel of the YUVLuminanceSource in the real app. // // Total number of pixels suffices, can ignore shape int size = width * height; luminances = new byte[size]; for (int offset = 0; offset < size; offset++) { int pixel = pixels[offset]; int r = (pixel >> 16) & 0xff; // red int g2 = (pixel >> 7) & 0x1fe; // 2 * green int b = pixel & 0xff; // blue // Calculate green-favouring average cheaply luminances[offset] = (byte) ((r + g2 + b) / 4); } } private RGBLuminanceSource(byte[] pixels, int dataWidth, int dataHeight, int left, int top, int width, int height) { super(width, height); if (left + width > dataWidth || top + height > dataHeight) { throw new IllegalArgumentException("Crop rectangle does not fit within image data."); } this.luminances = pixels; this.dataWidth = dataWidth; this.dataHeight = dataHeight; this.left = left; this.top = top; } @Override public byte[] getRow(int y, byte[] row) { if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException("Requested row is outside the image: " + y); } int width = getWidth(); if (row == null || row.length < width) { row = new byte[width]; } int offset = (y + top) * dataWidth + left; System.arraycopy(luminances, offset, row, 0, width); return row; } @Override public byte[] getMatrix() {<FILL_FUNCTION_BODY>} @Override public boolean isCropSupported() { return true; } @Override public LuminanceSource crop(int left, int top, int width, int height) { return new RGBLuminanceSource(luminances, dataWidth, dataHeight, this.left + left, this.top + top, width, height); } }
int width = getWidth(); int height = getHeight(); // If the caller asks for the entire underlying image, save the copy and give them the // original data. The docs specifically warn that result.length must be ignored. if (width == dataWidth && height == dataHeight) { return luminances; } int area = width * height; byte[] matrix = new byte[area]; int inputOffset = top * dataWidth + left; // If the width matches the full width of the underlying data, perform a single copy. if (width == dataWidth) { System.arraycopy(luminances, inputOffset, matrix, 0, area); return matrix; } // Otherwise copy one cropped row at a time. for (int y = 0; y < height; y++) { int outputOffset = y * width; System.arraycopy(luminances, inputOffset, matrix, outputOffset, width); inputOffset += dataWidth; } return matrix;
732
256
988
<methods>public com.google.zxing.LuminanceSource crop(int, int, int, int) ,public final int getHeight() ,public abstract byte[] getMatrix() ,public abstract byte[] getRow(int, byte[]) ,public final int getWidth() ,public com.google.zxing.LuminanceSource invert() ,public boolean isCropSupported() ,public boolean isRotateSupported() ,public com.google.zxing.LuminanceSource rotateCounterClockwise() ,public com.google.zxing.LuminanceSource rotateCounterClockwise45() ,public final java.lang.String toString() <variables>private final non-sealed int height,private final non-sealed int width
zxing_zxing
zxing/core/src/main/java/com/google/zxing/Result.java
Result
addResultPoints
class Result { private final String text; private final byte[] rawBytes; private final int numBits; private ResultPoint[] resultPoints; private final BarcodeFormat format; private Map<ResultMetadataType,Object> resultMetadata; private final long timestamp; public Result(String text, byte[] rawBytes, ResultPoint[] resultPoints, BarcodeFormat format) { this(text, rawBytes, resultPoints, format, System.currentTimeMillis()); } public Result(String text, byte[] rawBytes, ResultPoint[] resultPoints, BarcodeFormat format, long timestamp) { this(text, rawBytes, rawBytes == null ? 0 : 8 * rawBytes.length, resultPoints, format, timestamp); } public Result(String text, byte[] rawBytes, int numBits, ResultPoint[] resultPoints, BarcodeFormat format, long timestamp) { this.text = text; this.rawBytes = rawBytes; this.numBits = numBits; this.resultPoints = resultPoints; this.format = format; this.resultMetadata = null; this.timestamp = timestamp; } /** * @return raw text encoded by the barcode */ public String getText() { return text; } /** * @return raw bytes encoded by the barcode, if applicable, otherwise {@code null} */ public byte[] getRawBytes() { return rawBytes; } /** * @return how many bits of {@link #getRawBytes()} are valid; typically 8 times its length * @since 3.3.0 */ public int getNumBits() { return numBits; } /** * @return points related to the barcode in the image. These are typically points * identifying finder patterns or the corners of the barcode. The exact meaning is * specific to the type of barcode that was decoded. */ public ResultPoint[] getResultPoints() { return resultPoints; } /** * @return {@link BarcodeFormat} representing the format of the barcode that was decoded */ public BarcodeFormat getBarcodeFormat() { return format; } /** * @return {@link Map} mapping {@link ResultMetadataType} keys to values. May be * {@code null}. This contains optional metadata about what was detected about the barcode, * like orientation. */ public Map<ResultMetadataType,Object> getResultMetadata() { return resultMetadata; } public void putMetadata(ResultMetadataType type, Object value) { if (resultMetadata == null) { resultMetadata = new EnumMap<>(ResultMetadataType.class); } resultMetadata.put(type, value); } public void putAllMetadata(Map<ResultMetadataType,Object> metadata) { if (metadata != null) { if (resultMetadata == null) { resultMetadata = metadata; } else { resultMetadata.putAll(metadata); } } } public void addResultPoints(ResultPoint[] newPoints) {<FILL_FUNCTION_BODY>} public long getTimestamp() { return timestamp; } @Override public String toString() { return text; } }
ResultPoint[] oldPoints = resultPoints; if (oldPoints == null) { resultPoints = newPoints; } else if (newPoints != null && newPoints.length > 0) { ResultPoint[] allPoints = new ResultPoint[oldPoints.length + newPoints.length]; System.arraycopy(oldPoints, 0, allPoints, 0, oldPoints.length); System.arraycopy(newPoints, 0, allPoints, oldPoints.length, newPoints.length); resultPoints = allPoints; }
885
135
1,020
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/ResultPoint.java
ResultPoint
orderBestPatterns
class ResultPoint { private final float x; private final float y; public ResultPoint(float x, float y) { this.x = x; this.y = y; } public final float getX() { return x; } public final float getY() { return y; } @Override public final boolean equals(Object other) { if (other instanceof ResultPoint) { ResultPoint otherPoint = (ResultPoint) other; return x == otherPoint.x && y == otherPoint.y; } return false; } @Override public final int hashCode() { return 31 * Float.floatToIntBits(x) + Float.floatToIntBits(y); } @Override public final String toString() { return "(" + x + ',' + y + ')'; } /** * Orders an array of three ResultPoints in an order [A,B,C] such that AB is less than AC * and BC is less than AC, and the angle between BC and BA is less than 180 degrees. * * @param patterns array of three {@code ResultPoint} to order */ public static void orderBestPatterns(ResultPoint[] patterns) {<FILL_FUNCTION_BODY>} /** * @param pattern1 first pattern * @param pattern2 second pattern * @return distance between two points */ public static float distance(ResultPoint pattern1, ResultPoint pattern2) { return MathUtils.distance(pattern1.x, pattern1.y, pattern2.x, pattern2.y); } /** * Returns the z component of the cross product between vectors BC and BA. */ private static float crossProductZ(ResultPoint pointA, ResultPoint pointB, ResultPoint pointC) { float bX = pointB.x; float bY = pointB.y; return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX)); } }
// Find distances between pattern centers float zeroOneDistance = distance(patterns[0], patterns[1]); float oneTwoDistance = distance(patterns[1], patterns[2]); float zeroTwoDistance = distance(patterns[0], patterns[2]); ResultPoint pointA; ResultPoint pointB; ResultPoint pointC; // Assume one closest to other two is B; A and C will just be guesses at first if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) { pointB = patterns[0]; pointA = patterns[1]; pointC = patterns[2]; } else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) { pointB = patterns[1]; pointA = patterns[0]; pointC = patterns[2]; } else { pointB = patterns[2]; pointA = patterns[0]; pointC = patterns[1]; } // Use cross product to figure out whether A and C are correct or flipped. // This asks whether BC x BA has a positive z component, which is the arrangement // we want for A, B, C. If it's negative, then we've got it flipped around and // should swap A and C. if (crossProductZ(pointA, pointB, pointC) < 0.0f) { ResultPoint temp = pointA; pointA = pointC; pointC = temp; } patterns[0] = pointA; patterns[1] = pointB; patterns[2] = pointC;
550
401
951
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/aztec/AztecReader.java
AztecReader
decode
class AztecReader implements Reader { /** * Locates and decodes a Data Matrix code in an image. * * @return a String representing the content encoded by the Data Matrix code * @throws NotFoundException if a Data Matrix code cannot be found * @throws FormatException if a Data Matrix code cannot be decoded */ @Override public Result decode(BinaryBitmap image) throws NotFoundException, FormatException { return decode(image, null); } @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException {<FILL_FUNCTION_BODY>} @Override public void reset() { // do nothing } }
NotFoundException notFoundException = null; FormatException formatException = null; Detector detector = new Detector(image.getBlackMatrix()); ResultPoint[] points = null; DecoderResult decoderResult = null; int errorsCorrected = 0; try { AztecDetectorResult detectorResult = detector.detect(false); points = detectorResult.getPoints(); errorsCorrected = detectorResult.getErrorsCorrected(); decoderResult = new Decoder().decode(detectorResult); } catch (NotFoundException e) { notFoundException = e; } catch (FormatException e) { formatException = e; } if (decoderResult == null) { try { AztecDetectorResult detectorResult = detector.detect(true); points = detectorResult.getPoints(); errorsCorrected = detectorResult.getErrorsCorrected(); decoderResult = new Decoder().decode(detectorResult); } catch (NotFoundException | FormatException e) { if (notFoundException != null) { throw notFoundException; } if (formatException != null) { throw formatException; } throw e; } } if (hints != null) { ResultPointCallback rpcb = (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK); if (rpcb != null) { for (ResultPoint point : points) { rpcb.foundPossibleResultPoint(point); } } } Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), decoderResult.getNumBits(), points, BarcodeFormat.AZTEC, System.currentTimeMillis()); List<byte[]> byteSegments = decoderResult.getByteSegments(); if (byteSegments != null) { result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments); } String ecLevel = decoderResult.getECLevel(); if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } errorsCorrected += decoderResult.getErrorsCorrected(); result.putMetadata(ResultMetadataType.ERRORS_CORRECTED, errorsCorrected); result.putMetadata(ResultMetadataType.SYMBOLOGY_IDENTIFIER, "]z" + decoderResult.getSymbologyModifier()); return result;
194
662
856
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/aztec/AztecWriter.java
AztecWriter
encode
class AztecWriter implements Writer { @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) {<FILL_FUNCTION_BODY>} private static BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Charset charset, int eccPercent, int layers) { if (format != BarcodeFormat.AZTEC) { throw new IllegalArgumentException("Can only encode AZTEC, but got " + format); } AztecCode aztec = Encoder.encode(contents, eccPercent, layers, charset); return renderResult(aztec, width, height); } private static BitMatrix renderResult(AztecCode code, int width, int height) { BitMatrix input = code.getMatrix(); if (input == null) { throw new IllegalStateException(); } int inputWidth = input.getWidth(); int inputHeight = input.getHeight(); int outputWidth = Math.max(width, inputWidth); int outputHeight = Math.max(height, inputHeight); int multiple = Math.min(outputWidth / inputWidth, outputHeight / inputHeight); int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; int topPadding = (outputHeight - (inputHeight * multiple)) / 2; BitMatrix output = new BitMatrix(outputWidth, outputHeight); for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) { // Write the contents of this row of the barcode for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) { if (input.get(inputX, inputY)) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; } }
Charset charset = null; // Do not add any ECI code by default int eccPercent = Encoder.DEFAULT_EC_PERCENT; int layers = Encoder.DEFAULT_AZTEC_LAYERS; if (hints != null) { if (hints.containsKey(EncodeHintType.CHARACTER_SET)) { charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); } if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) { eccPercent = Integer.parseInt(hints.get(EncodeHintType.ERROR_CORRECTION).toString()); } if (hints.containsKey(EncodeHintType.AZTEC_LAYERS)) { layers = Integer.parseInt(hints.get(EncodeHintType.AZTEC_LAYERS).toString()); } } return encode(contents, format, width, height, charset, eccPercent, layers);
554
266
820
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/aztec/encoder/BinaryShiftToken.java
BinaryShiftToken
toString
class BinaryShiftToken extends Token { private final int binaryShiftStart; private final int binaryShiftByteCount; BinaryShiftToken(Token previous, int binaryShiftStart, int binaryShiftByteCount) { super(previous); this.binaryShiftStart = binaryShiftStart; this.binaryShiftByteCount = binaryShiftByteCount; } @Override public void appendTo(BitArray bitArray, byte[] text) { int bsbc = binaryShiftByteCount; for (int i = 0; i < bsbc; i++) { if (i == 0 || (i == 31 && bsbc <= 62)) { // We need a header before the first character, and before // character 31 when the total byte code is <= 62 bitArray.appendBits(31, 5); // BINARY_SHIFT if (bsbc > 62) { bitArray.appendBits(bsbc - 31, 16); } else if (i == 0) { // 1 <= binaryShiftByteCode <= 62 bitArray.appendBits(Math.min(bsbc, 31), 5); } else { // 32 <= binaryShiftCount <= 62 and i == 31 bitArray.appendBits(bsbc - 31, 5); } } bitArray.appendBits(text[binaryShiftStart + i], 8); } } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "<" + binaryShiftStart + "::" + (binaryShiftStart + binaryShiftByteCount - 1) + '>';
401
35
436
<methods><variables>static final com.google.zxing.aztec.encoder.Token EMPTY,private final non-sealed com.google.zxing.aztec.encoder.Token previous
zxing_zxing
zxing/core/src/main/java/com/google/zxing/aztec/encoder/SimpleToken.java
SimpleToken
toString
class SimpleToken extends Token { // For normal words, indicates value and bitCount private final short value; private final short bitCount; SimpleToken(Token previous, int value, int bitCount) { super(previous); this.value = (short) value; this.bitCount = (short) bitCount; } @Override void appendTo(BitArray bitArray, byte[] text) { bitArray.appendBits(value, bitCount); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
int value = this.value & ((1 << bitCount) - 1); value |= 1 << bitCount; return '<' + Integer.toBinaryString(value | (1 << bitCount)).substring(1) + '>';
152
62
214
<methods><variables>static final com.google.zxing.aztec.encoder.Token EMPTY,private final non-sealed com.google.zxing.aztec.encoder.Token previous
zxing_zxing
zxing/core/src/main/java/com/google/zxing/aztec/encoder/State.java
State
toBitArray
class State { static final State INITIAL_STATE = new State(Token.EMPTY, HighLevelEncoder.MODE_UPPER, 0, 0); // The current mode of the encoding (or the mode to which we'll return if // we're in Binary Shift mode. private final int mode; // The list of tokens that we output. If we are in Binary Shift mode, this // token list does *not* yet included the token for those bytes private final Token token; // If non-zero, the number of most recent bytes that should be output // in Binary Shift mode. private final int binaryShiftByteCount; // The total number of bits generated (including Binary Shift). private final int bitCount; private final int binaryShiftCost; private State(Token token, int mode, int binaryBytes, int bitCount) { this.token = token; this.mode = mode; this.binaryShiftByteCount = binaryBytes; this.bitCount = bitCount; this.binaryShiftCost = calculateBinaryShiftCost(binaryBytes); } int getMode() { return mode; } Token getToken() { return token; } int getBinaryShiftByteCount() { return binaryShiftByteCount; } int getBitCount() { return bitCount; } State appendFLGn(int eci) { State result = shiftAndAppend(HighLevelEncoder.MODE_PUNCT, 0); // 0: FLG(n) Token token = result.token; int bitsAdded = 3; if (eci < 0) { token = token.add(0, 3); // 0: FNC1 } else if (eci > 999999) { throw new IllegalArgumentException("ECI code must be between 0 and 999999"); } else { byte[] eciDigits = Integer.toString(eci).getBytes(StandardCharsets.ISO_8859_1); token = token.add(eciDigits.length, 3); // 1-6: number of ECI digits for (byte eciDigit : eciDigits) { token = token.add(eciDigit - '0' + 2, 4); } bitsAdded += eciDigits.length * 4; } return new State(token, mode, 0, bitCount + bitsAdded); } // Create a new state representing this state with a latch to a (not // necessary different) mode, and then a code. State latchAndAppend(int mode, int value) { int bitCount = this.bitCount; Token token = this.token; if (mode != this.mode) { int latch = HighLevelEncoder.LATCH_TABLE[this.mode][mode]; token = token.add(latch & 0xFFFF, latch >> 16); bitCount += latch >> 16; } int latchModeBitCount = mode == HighLevelEncoder.MODE_DIGIT ? 4 : 5; token = token.add(value, latchModeBitCount); return new State(token, mode, 0, bitCount + latchModeBitCount); } // Create a new state representing this state, with a temporary shift // to a different mode to output a single value. State shiftAndAppend(int mode, int value) { Token token = this.token; int thisModeBitCount = this.mode == HighLevelEncoder.MODE_DIGIT ? 4 : 5; // Shifts exist only to UPPER and PUNCT, both with tokens size 5. token = token.add(HighLevelEncoder.SHIFT_TABLE[this.mode][mode], thisModeBitCount); token = token.add(value, 5); return new State(token, this.mode, 0, this.bitCount + thisModeBitCount + 5); } // Create a new state representing this state, but an additional character // output in Binary Shift mode. State addBinaryShiftChar(int index) { Token token = this.token; int mode = this.mode; int bitCount = this.bitCount; if (this.mode == HighLevelEncoder.MODE_PUNCT || this.mode == HighLevelEncoder.MODE_DIGIT) { int latch = HighLevelEncoder.LATCH_TABLE[mode][HighLevelEncoder.MODE_UPPER]; token = token.add(latch & 0xFFFF, latch >> 16); bitCount += latch >> 16; mode = HighLevelEncoder.MODE_UPPER; } int deltaBitCount = (binaryShiftByteCount == 0 || binaryShiftByteCount == 31) ? 18 : (binaryShiftByteCount == 62) ? 9 : 8; State result = new State(token, mode, binaryShiftByteCount + 1, bitCount + deltaBitCount); if (result.binaryShiftByteCount == 2047 + 31) { // The string is as long as it's allowed to be. We should end it. result = result.endBinaryShift(index + 1); } return result; } // Create the state identical to this one, but we are no longer in // Binary Shift mode. State endBinaryShift(int index) { if (binaryShiftByteCount == 0) { return this; } Token token = this.token; token = token.addBinaryShift(index - binaryShiftByteCount, binaryShiftByteCount); return new State(token, mode, 0, this.bitCount); } // Returns true if "this" state is better (or equal) to be in than "that" // state under all possible circumstances. boolean isBetterThanOrEqualTo(State other) { int newModeBitCount = this.bitCount + (HighLevelEncoder.LATCH_TABLE[this.mode][other.mode] >> 16); if (this.binaryShiftByteCount < other.binaryShiftByteCount) { // add additional B/S encoding cost of other, if any newModeBitCount += other.binaryShiftCost - this.binaryShiftCost; } else if (this.binaryShiftByteCount > other.binaryShiftByteCount && other.binaryShiftByteCount > 0) { // maximum possible additional cost (we end up exceeding the 31 byte boundary and other state can stay beneath it) newModeBitCount += 10; } return newModeBitCount <= other.bitCount; } BitArray toBitArray(byte[] text) {<FILL_FUNCTION_BODY>} @Override public String toString() { return String.format("%s bits=%d bytes=%d", HighLevelEncoder.MODE_NAMES[mode], bitCount, binaryShiftByteCount); } private static int calculateBinaryShiftCost(int binaryShiftByteCount) { if (binaryShiftByteCount > 62) { return 21; // B/S with extended length } if (binaryShiftByteCount > 31) { return 20; // two B/S } if (binaryShiftByteCount > 0) { return 10; // one B/S } return 0; } }
List<Token> symbols = new ArrayList<>(); for (Token token = endBinaryShift(text.length).token; token != null; token = token.getPrevious()) { symbols.add(token); } BitArray bitArray = new BitArray(); // Add each token to the result in forward order for (int i = symbols.size() - 1; i >= 0; i--) { symbols.get(i).appendTo(bitArray, text); } return bitArray;
1,876
127
2,003
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/aztec/encoder/Token.java
Token
addBinaryShift
class Token { static final Token EMPTY = new SimpleToken(null, 0, 0); private final Token previous; Token(Token previous) { this.previous = previous; } final Token getPrevious() { return previous; } final Token add(int value, int bitCount) { return new SimpleToken(this, value, bitCount); } final Token addBinaryShift(int start, int byteCount) {<FILL_FUNCTION_BODY>} abstract void appendTo(BitArray bitArray, byte[] text); }
//int bitCount = (byteCount * 8) + (byteCount <= 31 ? 10 : byteCount <= 62 ? 20 : 21); return new BinaryShiftToken(this, start, byteCount);
159
59
218
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/AddressBookAUResultParser.java
AddressBookAUResultParser
parse
class AddressBookAUResultParser extends ResultParser { @Override public AddressBookParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} private static String[] matchMultipleValuePrefix(String prefix, String rawText) { List<String> values = null; // For now, always 3, and always trim for (int i = 1; i <= 3; i++) { String value = matchSinglePrefixedField(prefix + i + ':', rawText, '\r', true); if (value == null) { break; } if (values == null) { values = new ArrayList<>(3); // lazy init } values.add(value); } if (values == null) { return null; } return values.toArray(EMPTY_STR_ARRAY); } }
String rawText = getMassagedText(result); // MEMORY is mandatory; seems like a decent indicator, as does end-of-record separator CR/LF if (!rawText.contains("MEMORY") || !rawText.contains("\r\n")) { return null; } // NAME1 and NAME2 have specific uses, namely written name and pronunciation, respectively. // Therefore we treat them specially instead of as an array of names. String name = matchSinglePrefixedField("NAME1:", rawText, '\r', true); String pronunciation = matchSinglePrefixedField("NAME2:", rawText, '\r', true); String[] phoneNumbers = matchMultipleValuePrefix("TEL", rawText); String[] emails = matchMultipleValuePrefix("MAIL", rawText); String note = matchSinglePrefixedField("MEMORY:", rawText, '\r', false); String address = matchSinglePrefixedField("ADD:", rawText, '\r', true); String[] addresses = address == null ? null : new String[] {address}; return new AddressBookParsedResult(maybeWrap(name), null, pronunciation, phoneNumbers, null, emails, null, null, note, addresses, null, null, null, null, null, null);
221
342
563
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/AddressBookDoCoMoResultParser.java
AddressBookDoCoMoResultParser
parse
class AddressBookDoCoMoResultParser extends AbstractDoCoMoResultParser { @Override public AddressBookParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} private static String parseName(String name) { int comma = name.indexOf(','); if (comma >= 0) { // Format may be last,first; switch it around return name.substring(comma + 1) + ' ' + name.substring(0, comma); } return name; } }
String rawText = getMassagedText(result); if (!rawText.startsWith("MECARD:")) { return null; } String[] rawName = matchDoCoMoPrefixedField("N:", rawText); if (rawName == null) { return null; } String name = parseName(rawName[0]); String pronunciation = matchSingleDoCoMoPrefixedField("SOUND:", rawText, true); String[] phoneNumbers = matchDoCoMoPrefixedField("TEL:", rawText); String[] emails = matchDoCoMoPrefixedField("EMAIL:", rawText); String note = matchSingleDoCoMoPrefixedField("NOTE:", rawText, false); String[] addresses = matchDoCoMoPrefixedField("ADR:", rawText); String birthday = matchSingleDoCoMoPrefixedField("BDAY:", rawText, true); if (!isStringOfDigits(birthday, 8)) { // No reason to throw out the whole card because the birthday is formatted wrong. birthday = null; } String[] urls = matchDoCoMoPrefixedField("URL:", rawText); // Although ORG may not be strictly legal in MECARD, it does exist in VCARD and we might as well // honor it when found in the wild. String org = matchSingleDoCoMoPrefixedField("ORG:", rawText, true); return new AddressBookParsedResult(maybeWrap(name), null, pronunciation, phoneNumbers, null, emails, null, null, note, addresses, null, org, birthday, null, urls, null);
136
439
575
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/AddressBookParsedResult.java
AddressBookParsedResult
getDisplayResult
class AddressBookParsedResult extends ParsedResult { private final String[] names; private final String[] nicknames; private final String pronunciation; private final String[] phoneNumbers; private final String[] phoneTypes; private final String[] emails; private final String[] emailTypes; private final String instantMessenger; private final String note; private final String[] addresses; private final String[] addressTypes; private final String org; private final String birthday; private final String title; private final String[] urls; private final String[] geo; public AddressBookParsedResult(String[] names, String[] phoneNumbers, String[] phoneTypes, String[] emails, String[] emailTypes, String[] addresses, String[] addressTypes) { this(names, null, null, phoneNumbers, phoneTypes, emails, emailTypes, null, null, addresses, addressTypes, null, null, null, null, null); } public AddressBookParsedResult(String[] names, String[] nicknames, String pronunciation, String[] phoneNumbers, String[] phoneTypes, String[] emails, String[] emailTypes, String instantMessenger, String note, String[] addresses, String[] addressTypes, String org, String birthday, String title, String[] urls, String[] geo) { super(ParsedResultType.ADDRESSBOOK); if (phoneNumbers != null && phoneTypes != null && phoneNumbers.length != phoneTypes.length) { throw new IllegalArgumentException("Phone numbers and types lengths differ"); } if (emails != null && emailTypes != null && emails.length != emailTypes.length) { throw new IllegalArgumentException("Emails and types lengths differ"); } if (addresses != null && addressTypes != null && addresses.length != addressTypes.length) { throw new IllegalArgumentException("Addresses and types lengths differ"); } this.names = names; this.nicknames = nicknames; this.pronunciation = pronunciation; this.phoneNumbers = phoneNumbers; this.phoneTypes = phoneTypes; this.emails = emails; this.emailTypes = emailTypes; this.instantMessenger = instantMessenger; this.note = note; this.addresses = addresses; this.addressTypes = addressTypes; this.org = org; this.birthday = birthday; this.title = title; this.urls = urls; this.geo = geo; } public String[] getNames() { return names; } public String[] getNicknames() { return nicknames; } /** * In Japanese, the name is written in kanji, which can have multiple readings. Therefore a hint * is often provided, called furigana, which spells the name phonetically. * * @return The pronunciation of the getNames() field, often in hiragana or katakana. */ public String getPronunciation() { return pronunciation; } public String[] getPhoneNumbers() { return phoneNumbers; } /** * @return optional descriptions of the type of each phone number. It could be like "HOME", but, * there is no guaranteed or standard format. */ public String[] getPhoneTypes() { return phoneTypes; } public String[] getEmails() { return emails; } /** * @return optional descriptions of the type of each e-mail. It could be like "WORK", but, * there is no guaranteed or standard format. */ public String[] getEmailTypes() { return emailTypes; } public String getInstantMessenger() { return instantMessenger; } public String getNote() { return note; } public String[] getAddresses() { return addresses; } /** * @return optional descriptions of the type of each e-mail. It could be like "WORK", but, * there is no guaranteed or standard format. */ public String[] getAddressTypes() { return addressTypes; } public String getTitle() { return title; } public String getOrg() { return org; } public String[] getURLs() { return urls; } /** * @return birthday formatted as yyyyMMdd (e.g. 19780917) */ public String getBirthday() { return birthday; } /** * @return a location as a latitude/longitude pair */ public String[] getGeo() { return geo; } @Override public String getDisplayResult() {<FILL_FUNCTION_BODY>} }
StringBuilder result = new StringBuilder(100); maybeAppend(names, result); maybeAppend(nicknames, result); maybeAppend(pronunciation, result); maybeAppend(title, result); maybeAppend(org, result); maybeAppend(addresses, result); maybeAppend(phoneNumbers, result); maybeAppend(emails, result); maybeAppend(instantMessenger, result); maybeAppend(urls, result); maybeAppend(birthday, result); maybeAppend(geo, result); maybeAppend(note, result); return result.toString();
1,314
156
1,470
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/BizcardResultParser.java
BizcardResultParser
buildPhoneNumbers
class BizcardResultParser extends AbstractDoCoMoResultParser { // Yes, we extend AbstractDoCoMoResultParser since the format is very much // like the DoCoMo MECARD format, but this is not technically one of // DoCoMo's proposed formats @Override public AddressBookParsedResult parse(Result result) { String rawText = getMassagedText(result); if (!rawText.startsWith("BIZCARD:")) { return null; } String firstName = matchSingleDoCoMoPrefixedField("N:", rawText, true); String lastName = matchSingleDoCoMoPrefixedField("X:", rawText, true); String fullName = buildName(firstName, lastName); String title = matchSingleDoCoMoPrefixedField("T:", rawText, true); String org = matchSingleDoCoMoPrefixedField("C:", rawText, true); String[] addresses = matchDoCoMoPrefixedField("A:", rawText); String phoneNumber1 = matchSingleDoCoMoPrefixedField("B:", rawText, true); String phoneNumber2 = matchSingleDoCoMoPrefixedField("M:", rawText, true); String phoneNumber3 = matchSingleDoCoMoPrefixedField("F:", rawText, true); String email = matchSingleDoCoMoPrefixedField("E:", rawText, true); return new AddressBookParsedResult(maybeWrap(fullName), null, null, buildPhoneNumbers(phoneNumber1, phoneNumber2, phoneNumber3), null, maybeWrap(email), null, null, null, addresses, null, org, null, title, null, null); } private static String[] buildPhoneNumbers(String number1, String number2, String number3) {<FILL_FUNCTION_BODY>} private static String buildName(String firstName, String lastName) { if (firstName == null) { return lastName; } else { return lastName == null ? firstName : firstName + ' ' + lastName; } } }
List<String> numbers = new ArrayList<>(3); if (number1 != null) { numbers.add(number1); } if (number2 != null) { numbers.add(number2); } if (number3 != null) { numbers.add(number3); } int size = numbers.size(); if (size == 0) { return null; } return numbers.toArray(new String[size]);
551
125
676
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/BookmarkDoCoMoResultParser.java
BookmarkDoCoMoResultParser
parse
class BookmarkDoCoMoResultParser extends AbstractDoCoMoResultParser { @Override public URIParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} }
String rawText = result.getText(); if (!rawText.startsWith("MEBKM:")) { return null; } String title = matchSingleDoCoMoPrefixedField("TITLE:", rawText, true); String[] rawUri = matchDoCoMoPrefixedField("URL:", rawText); if (rawUri == null) { return null; } String uri = rawUri[0]; return URIResultParser.isBasicallyValidURI(uri) ? new URIParsedResult(uri, title) : null;
52
143
195
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/EmailAddressParsedResult.java
EmailAddressParsedResult
getDisplayResult
class EmailAddressParsedResult extends ParsedResult { private final String[] tos; private final String[] ccs; private final String[] bccs; private final String subject; private final String body; EmailAddressParsedResult(String to) { this(new String[] {to}, null, null, null, null); } EmailAddressParsedResult(String[] tos, String[] ccs, String[] bccs, String subject, String body) { super(ParsedResultType.EMAIL_ADDRESS); this.tos = tos; this.ccs = ccs; this.bccs = bccs; this.subject = subject; this.body = body; } /** * @return first elements of {@link #getTos()} or {@code null} if none * @deprecated use {@link #getTos()} */ @Deprecated public String getEmailAddress() { return tos == null || tos.length == 0 ? null : tos[0]; } public String[] getTos() { return tos; } public String[] getCCs() { return ccs; } public String[] getBCCs() { return bccs; } public String getSubject() { return subject; } public String getBody() { return body; } /** * @return "mailto:" * @deprecated without replacement */ @Deprecated public String getMailtoURI() { return "mailto:"; } @Override public String getDisplayResult() {<FILL_FUNCTION_BODY>} }
StringBuilder result = new StringBuilder(30); maybeAppend(tos, result); maybeAppend(ccs, result); maybeAppend(bccs, result); maybeAppend(subject, result); maybeAppend(body, result); return result.toString();
458
72
530
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/EmailAddressResultParser.java
EmailAddressResultParser
parse
class EmailAddressResultParser extends ResultParser { private static final Pattern COMMA = Pattern.compile(","); @Override public EmailAddressParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} }
String rawText = getMassagedText(result); if (rawText.startsWith("mailto:") || rawText.startsWith("MAILTO:")) { // If it starts with mailto:, assume it is definitely trying to be an email address String hostEmail = rawText.substring(7); int queryStart = hostEmail.indexOf('?'); if (queryStart >= 0) { hostEmail = hostEmail.substring(0, queryStart); } try { hostEmail = urlDecode(hostEmail); } catch (IllegalArgumentException iae) { return null; } String[] tos = null; if (!hostEmail.isEmpty()) { tos = COMMA.split(hostEmail); } Map<String,String> nameValues = parseNameValuePairs(rawText); String[] ccs = null; String[] bccs = null; String subject = null; String body = null; if (nameValues != null) { if (tos == null) { String tosString = nameValues.get("to"); if (tosString != null) { tos = COMMA.split(tosString); } } String ccString = nameValues.get("cc"); if (ccString != null) { ccs = COMMA.split(ccString); } String bccString = nameValues.get("bcc"); if (bccString != null) { bccs = COMMA.split(bccString); } subject = nameValues.get("subject"); body = nameValues.get("body"); } return new EmailAddressParsedResult(tos, ccs, bccs, subject, body); } else { if (!EmailDoCoMoResultParser.isBasicallyValidEmailAddress(rawText)) { return null; } return new EmailAddressParsedResult(rawText); }
63
500
563
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/EmailDoCoMoResultParser.java
EmailDoCoMoResultParser
isBasicallyValidEmailAddress
class EmailDoCoMoResultParser extends AbstractDoCoMoResultParser { private static final Pattern ATEXT_ALPHANUMERIC = Pattern.compile("[a-zA-Z0-9@.!#$%&'*+\\-/=?^_`{|}~]+"); @Override public EmailAddressParsedResult parse(Result result) { String rawText = getMassagedText(result); if (!rawText.startsWith("MATMSG:")) { return null; } String[] tos = matchDoCoMoPrefixedField("TO:", rawText); if (tos == null) { return null; } for (String to : tos) { if (!isBasicallyValidEmailAddress(to)) { return null; } } String subject = matchSingleDoCoMoPrefixedField("SUB:", rawText, false); String body = matchSingleDoCoMoPrefixedField("BODY:", rawText, false); return new EmailAddressParsedResult(tos, null, null, subject, body); } /** * This implements only the most basic checking for an email address's validity -- that it contains * an '@' and contains no characters disallowed by RFC 2822. This is an overly lenient definition of * validity. We want to generally be lenient here since this class is only intended to encapsulate what's * in a barcode, not "judge" it. */ static boolean isBasicallyValidEmailAddress(String email) {<FILL_FUNCTION_BODY>} }
return email != null && ATEXT_ALPHANUMERIC.matcher(email).matches() && email.indexOf('@') >= 0;
410
39
449
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/ExpandedProductParsedResult.java
ExpandedProductParsedResult
equals
class ExpandedProductParsedResult extends ParsedResult { public static final String KILOGRAM = "KG"; public static final String POUND = "LB"; private final String rawText; private final String productID; private final String sscc; private final String lotNumber; private final String productionDate; private final String packagingDate; private final String bestBeforeDate; private final String expirationDate; private final String weight; private final String weightType; private final String weightIncrement; private final String price; private final String priceIncrement; private final String priceCurrency; // For AIS that not exist in this object private final Map<String,String> uncommonAIs; public ExpandedProductParsedResult(String rawText, String productID, String sscc, String lotNumber, String productionDate, String packagingDate, String bestBeforeDate, String expirationDate, String weight, String weightType, String weightIncrement, String price, String priceIncrement, String priceCurrency, Map<String,String> uncommonAIs) { super(ParsedResultType.PRODUCT); this.rawText = rawText; this.productID = productID; this.sscc = sscc; this.lotNumber = lotNumber; this.productionDate = productionDate; this.packagingDate = packagingDate; this.bestBeforeDate = bestBeforeDate; this.expirationDate = expirationDate; this.weight = weight; this.weightType = weightType; this.weightIncrement = weightIncrement; this.price = price; this.priceIncrement = priceIncrement; this.priceCurrency = priceCurrency; this.uncommonAIs = uncommonAIs; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { int hash = Objects.hashCode(productID); hash ^= Objects.hashCode(sscc); hash ^= Objects.hashCode(lotNumber); hash ^= Objects.hashCode(productionDate); hash ^= Objects.hashCode(bestBeforeDate); hash ^= Objects.hashCode(expirationDate); hash ^= Objects.hashCode(weight); hash ^= Objects.hashCode(weightType); hash ^= Objects.hashCode(weightIncrement); hash ^= Objects.hashCode(price); hash ^= Objects.hashCode(priceIncrement); hash ^= Objects.hashCode(priceCurrency); hash ^= Objects.hashCode(uncommonAIs); return hash; } public String getRawText() { return rawText; } public String getProductID() { return productID; } public String getSscc() { return sscc; } public String getLotNumber() { return lotNumber; } public String getProductionDate() { return productionDate; } public String getPackagingDate() { return packagingDate; } public String getBestBeforeDate() { return bestBeforeDate; } public String getExpirationDate() { return expirationDate; } public String getWeight() { return weight; } public String getWeightType() { return weightType; } public String getWeightIncrement() { return weightIncrement; } public String getPrice() { return price; } public String getPriceIncrement() { return priceIncrement; } public String getPriceCurrency() { return priceCurrency; } public Map<String,String> getUncommonAIs() { return uncommonAIs; } @Override public String getDisplayResult() { return String.valueOf(rawText); } }
if (!(o instanceof ExpandedProductParsedResult)) { return false; } ExpandedProductParsedResult other = (ExpandedProductParsedResult) o; return Objects.equals(productID, other.productID) && Objects.equals(sscc, other.sscc) && Objects.equals(lotNumber, other.lotNumber) && Objects.equals(productionDate, other.productionDate) && Objects.equals(bestBeforeDate, other.bestBeforeDate) && Objects.equals(expirationDate, other.expirationDate) && Objects.equals(weight, other.weight) && Objects.equals(weightType, other.weightType) && Objects.equals(weightIncrement, other.weightIncrement) && Objects.equals(price, other.price) && Objects.equals(priceIncrement, other.priceIncrement) && Objects.equals(priceCurrency, other.priceCurrency) && Objects.equals(uncommonAIs, other.uncommonAIs);
1,061
273
1,334
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/ExpandedProductResultParser.java
ExpandedProductResultParser
parse
class ExpandedProductResultParser extends ResultParser { @Override public ExpandedProductParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} private static String findAIvalue(int i, String rawText) { char c = rawText.charAt(i); // First character must be a open parenthesis.If not, ERROR if (c != '(') { return null; } CharSequence rawTextAux = rawText.substring(i + 1); StringBuilder buf = new StringBuilder(); for (int index = 0; index < rawTextAux.length(); index++) { char currentChar = rawTextAux.charAt(index); if (currentChar == ')') { return buf.toString(); } if (currentChar < '0' || currentChar > '9') { return null; } buf.append(currentChar); } return buf.toString(); } private static String findValue(int i, String rawText) { StringBuilder buf = new StringBuilder(); String rawTextAux = rawText.substring(i); for (int index = 0; index < rawTextAux.length(); index++) { char c = rawTextAux.charAt(index); if (c == '(') { // We look for a new AI. If it doesn't exist (ERROR), we continue // with the iteration if (findAIvalue(index, rawTextAux) != null) { break; } buf.append('('); } else { buf.append(c); } } return buf.toString(); } }
BarcodeFormat format = result.getBarcodeFormat(); if (format != BarcodeFormat.RSS_EXPANDED) { // ExtendedProductParsedResult NOT created. Not a RSS Expanded barcode return null; } String rawText = getMassagedText(result); String productID = null; String sscc = null; String lotNumber = null; String productionDate = null; String packagingDate = null; String bestBeforeDate = null; String expirationDate = null; String weight = null; String weightType = null; String weightIncrement = null; String price = null; String priceIncrement = null; String priceCurrency = null; Map<String,String> uncommonAIs = new HashMap<>(); int i = 0; while (i < rawText.length()) { String ai = findAIvalue(i, rawText); if (ai == null) { // Error. Code doesn't match with RSS expanded pattern // ExtendedProductParsedResult NOT created. Not match with RSS Expanded pattern return null; } i += ai.length() + 2; String value = findValue(i, rawText); i += value.length(); switch (ai) { case "00": sscc = value; break; case "01": productID = value; break; case "10": lotNumber = value; break; case "11": productionDate = value; break; case "13": packagingDate = value; break; case "15": bestBeforeDate = value; break; case "17": expirationDate = value; break; case "3100": case "3101": case "3102": case "3103": case "3104": case "3105": case "3106": case "3107": case "3108": case "3109": weight = value; weightType = ExpandedProductParsedResult.KILOGRAM; weightIncrement = ai.substring(3); break; case "3200": case "3201": case "3202": case "3203": case "3204": case "3205": case "3206": case "3207": case "3208": case "3209": weight = value; weightType = ExpandedProductParsedResult.POUND; weightIncrement = ai.substring(3); break; case "3920": case "3921": case "3922": case "3923": price = value; priceIncrement = ai.substring(3); break; case "3930": case "3931": case "3932": case "3933": if (value.length() < 4) { // The value must have more of 3 symbols (3 for currency and // 1 at least for the price) // ExtendedProductParsedResult NOT created. Not match with RSS Expanded pattern return null; } price = value.substring(3); priceCurrency = value.substring(0, 3); priceIncrement = ai.substring(3); break; default: // No match with common AIs uncommonAIs.put(ai, value); break; } } return new ExpandedProductParsedResult(rawText, productID, sscc, lotNumber, productionDate, packagingDate, bestBeforeDate, expirationDate, weight, weightType, weightIncrement, price, priceIncrement, priceCurrency, uncommonAIs);
432
1,089
1,521
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/GeoParsedResult.java
GeoParsedResult
getDisplayResult
class GeoParsedResult extends ParsedResult { private final double latitude; private final double longitude; private final double altitude; private final String query; GeoParsedResult(double latitude, double longitude, double altitude, String query) { super(ParsedResultType.GEO); this.latitude = latitude; this.longitude = longitude; this.altitude = altitude; this.query = query; } public String getGeoURI() { StringBuilder result = new StringBuilder(); result.append("geo:"); result.append(latitude); result.append(','); result.append(longitude); if (altitude > 0) { result.append(','); result.append(altitude); } if (query != null) { result.append('?'); result.append(query); } return result.toString(); } /** * @return latitude in degrees */ public double getLatitude() { return latitude; } /** * @return longitude in degrees */ public double getLongitude() { return longitude; } /** * @return altitude in meters. If not specified, in the geo URI, returns 0.0 */ public double getAltitude() { return altitude; } /** * @return query string associated with geo URI or null if none exists */ public String getQuery() { return query; } @Override public String getDisplayResult() {<FILL_FUNCTION_BODY>} }
StringBuilder result = new StringBuilder(20); result.append(latitude); result.append(", "); result.append(longitude); if (altitude > 0.0) { result.append(", "); result.append(altitude); result.append('m'); } if (query != null) { result.append(" ("); result.append(query); result.append(')'); } return result.toString();
436
126
562
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/GeoResultParser.java
GeoResultParser
parse
class GeoResultParser extends ResultParser { private static final Pattern GEO_URL_PATTERN = Pattern.compile("geo:([\\-0-9.]+),([\\-0-9.]+)(?:,([\\-0-9.]+))?(?:\\?(.*))?", Pattern.CASE_INSENSITIVE); @Override public GeoParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} }
CharSequence rawText = getMassagedText(result); Matcher matcher = GEO_URL_PATTERN.matcher(rawText); if (!matcher.matches()) { return null; } String query = matcher.group(4); double latitude; double longitude; double altitude; try { latitude = Double.parseDouble(matcher.group(1)); if (latitude > 90.0 || latitude < -90.0) { return null; } longitude = Double.parseDouble(matcher.group(2)); if (longitude > 180.0 || longitude < -180.0) { return null; } if (matcher.group(3) == null) { altitude = 0.0; } else { altitude = Double.parseDouble(matcher.group(3)); if (altitude < 0.0) { return null; } } } catch (NumberFormatException ignored) { return null; } return new GeoParsedResult(latitude, longitude, altitude, query);
120
299
419
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/ISBNResultParser.java
ISBNResultParser
parse
class ISBNResultParser extends ResultParser { /** * See <a href="http://www.bisg.org/isbn-13/for.dummies.html">ISBN-13 For Dummies</a> */ @Override public ISBNParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} }
BarcodeFormat format = result.getBarcodeFormat(); if (format != BarcodeFormat.EAN_13) { return null; } String rawText = getMassagedText(result); int length = rawText.length(); if (length != 13) { return null; } if (!rawText.startsWith("978") && !rawText.startsWith("979")) { return null; } return new ISBNParsedResult(rawText);
95
140
235
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/ParsedResult.java
ParsedResult
maybeAppend
class ParsedResult { private final ParsedResultType type; protected ParsedResult(ParsedResultType type) { this.type = type; } public final ParsedResultType getType() { return type; } public abstract String getDisplayResult(); @Override public final String toString() { return getDisplayResult(); } public static void maybeAppend(String value, StringBuilder result) { if (value != null && !value.isEmpty()) { // Don't add a newline before the first value if (result.length() > 0) { result.append('\n'); } result.append(value); } } public static void maybeAppend(String[] values, StringBuilder result) {<FILL_FUNCTION_BODY>} }
if (values != null) { for (String value : values) { maybeAppend(value, result); } }
220
38
258
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/ProductResultParser.java
ProductResultParser
parse
class ProductResultParser extends ResultParser { // Treat all UPC and EAN variants as UPCs, in the sense that they are all product barcodes. @Override public ProductParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} }
BarcodeFormat format = result.getBarcodeFormat(); if (!(format == BarcodeFormat.UPC_A || format == BarcodeFormat.UPC_E || format == BarcodeFormat.EAN_8 || format == BarcodeFormat.EAN_13)) { return null; } String rawText = getMassagedText(result); if (!isStringOfDigits(rawText, rawText.length())) { return null; } // Not actually checking the checksum again here String normalizedProductID; // Expand UPC-E for purposes of searching if (format == BarcodeFormat.UPC_E && rawText.length() == 8) { normalizedProductID = UPCEReader.convertUPCEtoUPCA(rawText); } else { normalizedProductID = rawText; } return new ProductParsedResult(rawText, normalizedProductID);
71
239
310
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/SMSMMSResultParser.java
SMSMMSResultParser
parse
class SMSMMSResultParser extends ResultParser { @Override public SMSParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} private static void addNumberVia(Collection<String> numbers, Collection<String> vias, String numberPart) { int numberEnd = numberPart.indexOf(';'); if (numberEnd < 0) { numbers.add(numberPart); vias.add(null); } else { numbers.add(numberPart.substring(0, numberEnd)); String maybeVia = numberPart.substring(numberEnd + 1); String via; if (maybeVia.startsWith("via=")) { via = maybeVia.substring(4); } else { via = null; } vias.add(via); } } }
String rawText = getMassagedText(result); if (!(rawText.startsWith("sms:") || rawText.startsWith("SMS:") || rawText.startsWith("mms:") || rawText.startsWith("MMS:"))) { return null; } // Check up front if this is a URI syntax string with query arguments Map<String,String> nameValuePairs = parseNameValuePairs(rawText); String subject = null; String body = null; boolean querySyntax = false; if (nameValuePairs != null && !nameValuePairs.isEmpty()) { subject = nameValuePairs.get("subject"); body = nameValuePairs.get("body"); querySyntax = true; } // Drop sms, query portion int queryStart = rawText.indexOf('?', 4); String smsURIWithoutQuery; // If it's not query syntax, the question mark is part of the subject or message if (queryStart < 0 || !querySyntax) { smsURIWithoutQuery = rawText.substring(4); } else { smsURIWithoutQuery = rawText.substring(4, queryStart); } int lastComma = -1; int comma; List<String> numbers = new ArrayList<>(1); List<String> vias = new ArrayList<>(1); while ((comma = smsURIWithoutQuery.indexOf(',', lastComma + 1)) > lastComma) { String numberPart = smsURIWithoutQuery.substring(lastComma + 1, comma); addNumberVia(numbers, vias, numberPart); lastComma = comma; } addNumberVia(numbers, vias, smsURIWithoutQuery.substring(lastComma + 1)); return new SMSParsedResult(numbers.toArray(EMPTY_STR_ARRAY), vias.toArray(EMPTY_STR_ARRAY), subject, body);
224
515
739
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/SMSParsedResult.java
SMSParsedResult
getDisplayResult
class SMSParsedResult extends ParsedResult { private final String[] numbers; private final String[] vias; private final String subject; private final String body; public SMSParsedResult(String number, String via, String subject, String body) { super(ParsedResultType.SMS); this.numbers = new String[] {number}; this.vias = new String[] {via}; this.subject = subject; this.body = body; } public SMSParsedResult(String[] numbers, String[] vias, String subject, String body) { super(ParsedResultType.SMS); this.numbers = numbers; this.vias = vias; this.subject = subject; this.body = body; } public String getSMSURI() { StringBuilder result = new StringBuilder(); result.append("sms:"); boolean first = true; for (int i = 0; i < numbers.length; i++) { if (first) { first = false; } else { result.append(','); } result.append(numbers[i]); if (vias != null && vias[i] != null) { result.append(";via="); result.append(vias[i]); } } boolean hasBody = body != null; boolean hasSubject = subject != null; if (hasBody || hasSubject) { result.append('?'); if (hasBody) { result.append("body="); result.append(body); } if (hasSubject) { if (hasBody) { result.append('&'); } result.append("subject="); result.append(subject); } } return result.toString(); } public String[] getNumbers() { return numbers; } public String[] getVias() { return vias; } public String getSubject() { return subject; } public String getBody() { return body; } @Override public String getDisplayResult() {<FILL_FUNCTION_BODY>} }
StringBuilder result = new StringBuilder(100); maybeAppend(numbers, result); maybeAppend(subject, result); maybeAppend(body, result); return result.toString();
593
52
645
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/SMSTOMMSTOResultParser.java
SMSTOMMSTOResultParser
parse
class SMSTOMMSTOResultParser extends ResultParser { @Override public SMSParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} }
String rawText = getMassagedText(result); if (!(rawText.startsWith("smsto:") || rawText.startsWith("SMSTO:") || rawText.startsWith("mmsto:") || rawText.startsWith("MMSTO:"))) { return null; } // Thanks to dominik.wild for suggesting this enhancement to support // smsto:number:body URIs String number = rawText.substring(6); String body = null; int bodyStart = number.indexOf(':'); if (bodyStart >= 0) { body = number.substring(bodyStart + 1); number = number.substring(0, bodyStart); } return new SMSParsedResult(number, null, null, body);
50
200
250
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/SMTPResultParser.java
SMTPResultParser
parse
class SMTPResultParser extends ResultParser { @Override public EmailAddressParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} }
String rawText = getMassagedText(result); if (!(rawText.startsWith("smtp:") || rawText.startsWith("SMTP:"))) { return null; } String emailAddress = rawText.substring(5); String subject = null; String body = null; int colon = emailAddress.indexOf(':'); if (colon >= 0) { subject = emailAddress.substring(colon + 1); emailAddress = emailAddress.substring(0, colon); colon = subject.indexOf(':'); if (colon >= 0) { body = subject.substring(colon + 1); subject = subject.substring(0, colon); } } return new EmailAddressParsedResult(new String[] {emailAddress}, null, null, subject, body);
44
216
260
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/TelParsedResult.java
TelParsedResult
getDisplayResult
class TelParsedResult extends ParsedResult { private final String number; private final String telURI; private final String title; public TelParsedResult(String number, String telURI, String title) { super(ParsedResultType.TEL); this.number = number; this.telURI = telURI; this.title = title; } public String getNumber() { return number; } public String getTelURI() { return telURI; } public String getTitle() { return title; } @Override public String getDisplayResult() {<FILL_FUNCTION_BODY>} }
StringBuilder result = new StringBuilder(20); maybeAppend(number, result); maybeAppend(title, result); return result.toString();
183
41
224
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/TelResultParser.java
TelResultParser
parse
class TelResultParser extends ResultParser { @Override public TelParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} }
String rawText = getMassagedText(result); if (!rawText.startsWith("tel:") && !rawText.startsWith("TEL:")) { return null; } // Normalize "TEL:" to "tel:" String telURI = rawText.startsWith("TEL:") ? "tel:" + rawText.substring(4) : rawText; // Drop tel, query portion int queryStart = rawText.indexOf('?', 4); String number = queryStart < 0 ? rawText.substring(4) : rawText.substring(4, queryStart); return new TelParsedResult(number, telURI, null);
43
173
216
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/URIParsedResult.java
URIParsedResult
getDisplayResult
class URIParsedResult extends ParsedResult { private final String uri; private final String title; public URIParsedResult(String uri, String title) { super(ParsedResultType.URI); this.uri = massageURI(uri); this.title = title; } public String getURI() { return uri; } public String getTitle() { return title; } /** * @return true if the URI contains suspicious patterns that may suggest it intends to * mislead the user about its true nature * @deprecated see {@link URIResultParser#isPossiblyMaliciousURI(String)} */ @Deprecated public boolean isPossiblyMaliciousURI() { return URIResultParser.isPossiblyMaliciousURI(uri); } @Override public String getDisplayResult() {<FILL_FUNCTION_BODY>} /** * Transforms a string that represents a URI into something more proper, by adding or canonicalizing * the protocol. */ private static String massageURI(String uri) { uri = uri.trim(); int protocolEnd = uri.indexOf(':'); if (protocolEnd < 0 || isColonFollowedByPortNumber(uri, protocolEnd)) { // No protocol, or found a colon, but it looks like it is after the host, so the protocol is still missing, // so assume http uri = "http://" + uri; } return uri; } private static boolean isColonFollowedByPortNumber(String uri, int protocolEnd) { int start = protocolEnd + 1; int nextSlash = uri.indexOf('/', start); if (nextSlash < 0) { nextSlash = uri.length(); } return ResultParser.isSubstringOfDigits(uri, start, nextSlash - start); } }
StringBuilder result = new StringBuilder(30); maybeAppend(title, result); maybeAppend(uri, result); return result.toString();
486
41
527
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/URIResultParser.java
URIResultParser
isBasicallyValidURI
class URIResultParser extends ResultParser { private static final Pattern ALLOWED_URI_CHARS_PATTERN = Pattern.compile("[-._~:/?#\\[\\]@!$&'()*+,;=%A-Za-z0-9]+"); private static final Pattern USER_IN_HOST = Pattern.compile(":/*([^/@]+)@[^/]+"); // See http://www.ietf.org/rfc/rfc2396.txt private static final Pattern URL_WITH_PROTOCOL_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9+-.]+:"); private static final Pattern URL_WITHOUT_PROTOCOL_PATTERN = Pattern.compile( "([a-zA-Z0-9\\-]+\\.){1,6}[a-zA-Z]{2,}" + // host name elements; allow up to say 6 domain elements "(:\\d{1,5})?" + // maybe port "(/|\\?|$)"); // query, path or nothing @Override public URIParsedResult parse(Result result) { String rawText = getMassagedText(result); // We specifically handle the odd "URL" scheme here for simplicity and add "URI" for fun // Assume anything starting this way really means to be a URI if (rawText.startsWith("URL:") || rawText.startsWith("URI:")) { return new URIParsedResult(rawText.substring(4).trim(), null); } rawText = rawText.trim(); if (!isBasicallyValidURI(rawText) || isPossiblyMaliciousURI(rawText)) { return null; } return new URIParsedResult(rawText, null); } /** * @return true if the URI contains suspicious patterns that may suggest it intends to * mislead the user about its true nature. At the moment this looks for the presence * of user/password syntax in the host/authority portion of a URI which may be used * in attempts to make the URI's host appear to be other than it is. Example: * http://yourbank.com@phisher.com This URI connects to phisher.com but may appear * to connect to yourbank.com at first glance. */ static boolean isPossiblyMaliciousURI(String uri) { return !ALLOWED_URI_CHARS_PATTERN.matcher(uri).matches() || USER_IN_HOST.matcher(uri).find(); } static boolean isBasicallyValidURI(String uri) {<FILL_FUNCTION_BODY>} }
if (uri.contains(" ")) { // Quick hack check for a common case return false; } Matcher m = URL_WITH_PROTOCOL_PATTERN.matcher(uri); if (m.find() && m.start() == 0) { // match at start only return true; } m = URL_WITHOUT_PROTOCOL_PATTERN.matcher(uri); return m.find() && m.start() == 0;
694
122
816
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/URLTOResultParser.java
URLTOResultParser
parse
class URLTOResultParser extends ResultParser { @Override public URIParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} }
String rawText = getMassagedText(result); if (!rawText.startsWith("urlto:") && !rawText.startsWith("URLTO:")) { return null; } int titleEnd = rawText.indexOf(':', 6); if (titleEnd < 0) { return null; } String title = titleEnd <= 6 ? null : rawText.substring(6, titleEnd); String uri = rawText.substring(titleEnd + 1); return new URIParsedResult(uri, title);
47
141
188
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/VEventResultParser.java
VEventResultParser
parse
class VEventResultParser extends ResultParser { @Override public CalendarParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} private static String matchSingleVCardPrefixedField(CharSequence prefix, String rawText) { List<String> values = VCardResultParser.matchSingleVCardPrefixedField(prefix, rawText, true, false); return values == null || values.isEmpty() ? null : values.get(0); } private static String[] matchVCardPrefixedField(CharSequence prefix, String rawText) { List<List<String>> values = VCardResultParser.matchVCardPrefixedField(prefix, rawText, true, false); if (values == null || values.isEmpty()) { return null; } int size = values.size(); String[] result = new String[size]; for (int i = 0; i < size; i++) { result[i] = values.get(i).get(0); } return result; } private static String stripMailto(String s) { if (s != null && (s.startsWith("mailto:") || s.startsWith("MAILTO:"))) { s = s.substring(7); } return s; } }
String rawText = getMassagedText(result); int vEventStart = rawText.indexOf("BEGIN:VEVENT"); if (vEventStart < 0) { return null; } String summary = matchSingleVCardPrefixedField("SUMMARY", rawText); String start = matchSingleVCardPrefixedField("DTSTART", rawText); if (start == null) { return null; } String end = matchSingleVCardPrefixedField("DTEND", rawText); String duration = matchSingleVCardPrefixedField("DURATION", rawText); String location = matchSingleVCardPrefixedField("LOCATION", rawText); String organizer = stripMailto(matchSingleVCardPrefixedField("ORGANIZER", rawText)); String[] attendees = matchVCardPrefixedField("ATTENDEE", rawText); if (attendees != null) { for (int i = 0; i < attendees.length; i++) { attendees[i] = stripMailto(attendees[i]); } } String description = matchSingleVCardPrefixedField("DESCRIPTION", rawText); String geoString = matchSingleVCardPrefixedField("GEO", rawText); double latitude; double longitude; if (geoString == null) { latitude = Double.NaN; longitude = Double.NaN; } else { int semicolon = geoString.indexOf(';'); if (semicolon < 0) { return null; } try { latitude = Double.parseDouble(geoString.substring(0, semicolon)); longitude = Double.parseDouble(geoString.substring(semicolon + 1)); } catch (NumberFormatException ignored) { return null; } } try { return new CalendarParsedResult(summary, start, end, duration, location, organizer, attendees, description, latitude, longitude); } catch (IllegalArgumentException ignored) { return null; }
332
542
874
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/VINParsedResult.java
VINParsedResult
getDisplayResult
class VINParsedResult extends ParsedResult { private final String vin; private final String worldManufacturerID; private final String vehicleDescriptorSection; private final String vehicleIdentifierSection; private final String countryCode; private final String vehicleAttributes; private final int modelYear; private final char plantCode; private final String sequentialNumber; public VINParsedResult(String vin, String worldManufacturerID, String vehicleDescriptorSection, String vehicleIdentifierSection, String countryCode, String vehicleAttributes, int modelYear, char plantCode, String sequentialNumber) { super(ParsedResultType.VIN); this.vin = vin; this.worldManufacturerID = worldManufacturerID; this.vehicleDescriptorSection = vehicleDescriptorSection; this.vehicleIdentifierSection = vehicleIdentifierSection; this.countryCode = countryCode; this.vehicleAttributes = vehicleAttributes; this.modelYear = modelYear; this.plantCode = plantCode; this.sequentialNumber = sequentialNumber; } public String getVIN() { return vin; } public String getWorldManufacturerID() { return worldManufacturerID; } public String getVehicleDescriptorSection() { return vehicleDescriptorSection; } public String getVehicleIdentifierSection() { return vehicleIdentifierSection; } public String getCountryCode() { return countryCode; } public String getVehicleAttributes() { return vehicleAttributes; } public int getModelYear() { return modelYear; } public char getPlantCode() { return plantCode; } public String getSequentialNumber() { return sequentialNumber; } @Override public String getDisplayResult() {<FILL_FUNCTION_BODY>} }
StringBuilder result = new StringBuilder(50); result.append(worldManufacturerID).append(' '); result.append(vehicleDescriptorSection).append(' '); result.append(vehicleIdentifierSection).append('\n'); if (countryCode != null) { result.append(countryCode).append(' '); } result.append(modelYear).append(' '); result.append(plantCode).append(' '); result.append(sequentialNumber).append('\n'); return result.toString();
502
140
642
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/VINResultParser.java
VINResultParser
parse
class VINResultParser extends ResultParser { private static final Pattern IOQ = Pattern.compile("[IOQ]"); private static final Pattern AZ09 = Pattern.compile("[A-Z0-9]{17}"); @Override public VINParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} private static boolean checkChecksum(CharSequence vin) { int sum = 0; for (int i = 0; i < vin.length(); i++) { sum += vinPositionWeight(i + 1) * vinCharValue(vin.charAt(i)); } char checkChar = vin.charAt(8); char expectedCheckChar = checkChar(sum % 11); return checkChar == expectedCheckChar; } private static int vinCharValue(char c) { if (c >= 'A' && c <= 'I') { return (c - 'A') + 1; } if (c >= 'J' && c <= 'R') { return (c - 'J') + 1; } if (c >= 'S' && c <= 'Z') { return (c - 'S') + 2; } if (c >= '0' && c <= '9') { return c - '0'; } throw new IllegalArgumentException(); } private static int vinPositionWeight(int position) { if (position >= 1 && position <= 7) { return 9 - position; } if (position == 8) { return 10; } if (position == 9) { return 0; } if (position >= 10 && position <= 17) { return 19 - position; } throw new IllegalArgumentException(); } private static char checkChar(int remainder) { if (remainder < 10) { return (char) ('0' + remainder); } if (remainder == 10) { return 'X'; } throw new IllegalArgumentException(); } private static int modelYear(char c) { if (c >= 'E' && c <= 'H') { return (c - 'E') + 1984; } if (c >= 'J' && c <= 'N') { return (c - 'J') + 1988; } if (c == 'P') { return 1993; } if (c >= 'R' && c <= 'T') { return (c - 'R') + 1994; } if (c >= 'V' && c <= 'Y') { return (c - 'V') + 1997; } if (c >= '1' && c <= '9') { return (c - '1') + 2001; } if (c >= 'A' && c <= 'D') { return (c - 'A') + 2010; } throw new IllegalArgumentException(); } private static String countryCode(CharSequence wmi) { char c1 = wmi.charAt(0); char c2 = wmi.charAt(1); switch (c1) { case '1': case '4': case '5': return "US"; case '2': return "CA"; case '3': if (c2 >= 'A' && c2 <= 'W') { return "MX"; } break; case '9': if ((c2 >= 'A' && c2 <= 'E') || (c2 >= '3' && c2 <= '9')) { return "BR"; } break; case 'J': if (c2 >= 'A' && c2 <= 'T') { return "JP"; } break; case 'K': if (c2 >= 'L' && c2 <= 'R') { return "KO"; } break; case 'L': return "CN"; case 'M': if (c2 >= 'A' && c2 <= 'E') { return "IN"; } break; case 'S': if (c2 >= 'A' && c2 <= 'M') { return "UK"; } if (c2 >= 'N' && c2 <= 'T') { return "DE"; } break; case 'V': if (c2 >= 'F' && c2 <= 'R') { return "FR"; } if (c2 >= 'S' && c2 <= 'W') { return "ES"; } break; case 'W': return "DE"; case 'X': if (c2 == '0' || (c2 >= '3' && c2 <= '9')) { return "RU"; } break; case 'Z': if (c2 >= 'A' && c2 <= 'R') { return "IT"; } break; } return null; } }
if (result.getBarcodeFormat() != BarcodeFormat.CODE_39) { return null; } String rawText = result.getText(); rawText = IOQ.matcher(rawText).replaceAll("").trim(); if (!AZ09.matcher(rawText).matches()) { return null; } try { if (!checkChecksum(rawText)) { return null; } String wmi = rawText.substring(0, 3); return new VINParsedResult(rawText, wmi, rawText.substring(3, 9), rawText.substring(9, 17), countryCode(wmi), rawText.substring(3, 8), modelYear(rawText.charAt(9)), rawText.charAt(10), rawText.substring(11)); } catch (IllegalArgumentException iae) { return null; }
1,321
257
1,578
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/WifiParsedResult.java
WifiParsedResult
getDisplayResult
class WifiParsedResult extends ParsedResult { private final String ssid; private final String networkEncryption; private final String password; private final boolean hidden; private final String identity; private final String anonymousIdentity; private final String eapMethod; private final String phase2Method; public WifiParsedResult(String networkEncryption, String ssid, String password) { this(networkEncryption, ssid, password, false); } public WifiParsedResult(String networkEncryption, String ssid, String password, boolean hidden) { this(networkEncryption, ssid, password, hidden, null, null, null, null); } public WifiParsedResult(String networkEncryption, String ssid, String password, boolean hidden, String identity, String anonymousIdentity, String eapMethod, String phase2Method) { super(ParsedResultType.WIFI); this.ssid = ssid; this.networkEncryption = networkEncryption; this.password = password; this.hidden = hidden; this.identity = identity; this.anonymousIdentity = anonymousIdentity; this.eapMethod = eapMethod; this.phase2Method = phase2Method; } public String getSsid() { return ssid; } public String getNetworkEncryption() { return networkEncryption; } public String getPassword() { return password; } public boolean isHidden() { return hidden; } public String getIdentity() { return identity; } public String getAnonymousIdentity() { return anonymousIdentity; } public String getEapMethod() { return eapMethod; } public String getPhase2Method() { return phase2Method; } @Override public String getDisplayResult() {<FILL_FUNCTION_BODY>} }
StringBuilder result = new StringBuilder(80); maybeAppend(ssid, result); maybeAppend(networkEncryption, result); maybeAppend(password, result); maybeAppend(Boolean.toString(hidden), result); return result.toString();
514
66
580
<methods>public abstract java.lang.String getDisplayResult() ,public final com.google.zxing.client.result.ParsedResultType getType() ,public static void maybeAppend(java.lang.String, java.lang.StringBuilder) ,public static void maybeAppend(java.lang.String[], java.lang.StringBuilder) ,public final java.lang.String toString() <variables>private final non-sealed com.google.zxing.client.result.ParsedResultType type
zxing_zxing
zxing/core/src/main/java/com/google/zxing/client/result/WifiResultParser.java
WifiResultParser
parse
class WifiResultParser extends ResultParser { @Override public WifiParsedResult parse(Result result) {<FILL_FUNCTION_BODY>} }
String rawText = getMassagedText(result); if (!rawText.startsWith("WIFI:")) { return null; } rawText = rawText.substring("WIFI:".length()); String ssid = matchSinglePrefixedField("S:", rawText, ';', false); if (ssid == null || ssid.isEmpty()) { return null; } String pass = matchSinglePrefixedField("P:", rawText, ';', false); String type = matchSinglePrefixedField("T:", rawText, ';', false); if (type == null) { type = "nopass"; } // Unfortunately, in the past, H: was not just used for boolean 'hidden', but 'phase 2 method'. // To try to retain backwards compatibility, we set one or the other based on whether the string // is 'true' or 'false': boolean hidden = false; String phase2Method = matchSinglePrefixedField("PH2:", rawText, ';', false); String hValue = matchSinglePrefixedField("H:", rawText, ';', false); if (hValue != null) { // If PH2 was specified separately, or if the value is clearly boolean, interpret it as 'hidden' if (phase2Method != null || "true".equalsIgnoreCase(hValue) || "false".equalsIgnoreCase(hValue)) { hidden = Boolean.parseBoolean(hValue); } else { phase2Method = hValue; } } String identity = matchSinglePrefixedField("I:", rawText, ';', false); String anonymousIdentity = matchSinglePrefixedField("A:", rawText, ';', false); String eapMethod = matchSinglePrefixedField("E:", rawText, ';', false); return new WifiParsedResult(type, ssid, pass, hidden, identity, anonymousIdentity, eapMethod, phase2Method);
44
487
531
<methods>public non-sealed void <init>() ,public abstract com.google.zxing.client.result.ParsedResult parse(com.google.zxing.Result) ,public static com.google.zxing.client.result.ParsedResult parseResult(com.google.zxing.Result) <variables>private static final java.util.regex.Pattern AMPERSAND,private static final java.lang.String BYTE_ORDER_MARK,private static final java.util.regex.Pattern DIGITS,static final java.lang.String[] EMPTY_STR_ARRAY,private static final java.util.regex.Pattern EQUALS,private static final com.google.zxing.client.result.ResultParser[] PARSERS
zxing_zxing
zxing/core/src/main/java/com/google/zxing/common/BitSource.java
BitSource
readBits
class BitSource { private final byte[] bytes; private int byteOffset; private int bitOffset; /** * @param bytes bytes from which this will read bits. Bits will be read from the first byte first. * Bits are read within a byte from most-significant to least-significant bit. */ public BitSource(byte[] bytes) { this.bytes = bytes; } /** * @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}. */ public int getBitOffset() { return bitOffset; } /** * @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}. */ public int getByteOffset() { return byteOffset; } /** * @param numBits number of bits to read * @return int representing the bits read. The bits will appear as the least-significant * bits of the int * @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available */ public int readBits(int numBits) {<FILL_FUNCTION_BODY>} /** * @return number of bits that can be read successfully */ public int available() { return 8 * (bytes.length - byteOffset) - bitOffset; } }
if (numBits < 1 || numBits > 32 || numBits > available()) { throw new IllegalArgumentException(String.valueOf(numBits)); } int result = 0; // First, read remainder from current byte if (bitOffset > 0) { int bitsLeft = 8 - bitOffset; int toRead = Math.min(numBits, bitsLeft); int bitsToNotRead = bitsLeft - toRead; int mask = (0xFF >> (8 - toRead)) << bitsToNotRead; result = (bytes[byteOffset] & mask) >> bitsToNotRead; numBits -= toRead; bitOffset += toRead; if (bitOffset == 8) { bitOffset = 0; byteOffset++; } } // Next read whole bytes if (numBits > 0) { while (numBits >= 8) { result = (result << 8) | (bytes[byteOffset] & 0xFF); byteOffset++; numBits -= 8; } // Finally read a partial byte if (numBits > 0) { int bitsToNotRead = 8 - numBits; int mask = (0xFF >> bitsToNotRead) << bitsToNotRead; result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead); bitOffset += numBits; } } return result;
367
378
745
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/common/DefaultGridSampler.java
DefaultGridSampler
sampleGrid
class DefaultGridSampler extends GridSampler { @Override public BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY) throws NotFoundException { PerspectiveTransform transform = PerspectiveTransform.quadrilateralToQuadrilateral( p1ToX, p1ToY, p2ToX, p2ToY, p3ToX, p3ToY, p4ToX, p4ToY, p1FromX, p1FromY, p2FromX, p2FromY, p3FromX, p3FromY, p4FromX, p4FromY); return sampleGrid(image, dimensionX, dimensionY, transform); } @Override public BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform) throws NotFoundException {<FILL_FUNCTION_BODY>} }
if (dimensionX <= 0 || dimensionY <= 0) { throw NotFoundException.getNotFoundInstance(); } BitMatrix bits = new BitMatrix(dimensionX, dimensionY); float[] points = new float[2 * dimensionX]; for (int y = 0; y < dimensionY; y++) { int max = points.length; float iValue = y + 0.5f; for (int x = 0; x < max; x += 2) { points[x] = (float) (x / 2) + 0.5f; points[x + 1] = iValue; } transform.transformPoints(points); // Quick check to see if points transformed to something inside the image; // sufficient to check the endpoints checkAndNudgePoints(image, points); try { for (int x = 0; x < max; x += 2) { if (image.get((int) points[x], (int) points[x + 1])) { // Black(-ish) pixel bits.set(x / 2, y); } } } catch (ArrayIndexOutOfBoundsException aioobe) { // This feels wrong, but, sometimes if the finder patterns are misidentified, the resulting // transform gets "twisted" such that it maps a straight line of points to a set of points // whose endpoints are in bounds, but others are not. There is probably some mathematical // way to detect this about the transformation that I don't know yet. // This results in an ugly runtime exception despite our clever checks above -- can't have // that. We could check each point's coordinates but that feels duplicative. We settle for // catching and wrapping ArrayIndexOutOfBoundsException. throw NotFoundException.getNotFoundInstance(); } } return bits;
338
455
793
<methods>public non-sealed void <init>() ,public static com.google.zxing.common.GridSampler getInstance() ,public abstract com.google.zxing.common.BitMatrix sampleGrid(com.google.zxing.common.BitMatrix, int, int, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float, float) throws com.google.zxing.NotFoundException,public abstract com.google.zxing.common.BitMatrix sampleGrid(com.google.zxing.common.BitMatrix, int, int, com.google.zxing.common.PerspectiveTransform) throws com.google.zxing.NotFoundException,public static void setGridSampler(com.google.zxing.common.GridSampler) <variables>private static com.google.zxing.common.GridSampler gridSampler
zxing_zxing
zxing/core/src/main/java/com/google/zxing/common/ECIEncoderSet.java
ECIEncoderSet
canEncode
class ECIEncoderSet { // List of encoders that potentially encode characters not in ISO-8859-1 in one byte. private static final List<CharsetEncoder> ENCODERS = new ArrayList<>(); static { String[] names = { "IBM437", "ISO-8859-2", "ISO-8859-3", "ISO-8859-4", "ISO-8859-5", "ISO-8859-6", "ISO-8859-7", "ISO-8859-8", "ISO-8859-9", "ISO-8859-10", "ISO-8859-11", "ISO-8859-13", "ISO-8859-14", "ISO-8859-15", "ISO-8859-16", "windows-1250", "windows-1251", "windows-1252", "windows-1256", "Shift_JIS" }; for (String name : names) { if (CharacterSetECI.getCharacterSetECIByName(name) != null) { try { ENCODERS.add(Charset.forName(name).newEncoder()); } catch (UnsupportedCharsetException e) { // continue } } } } private final CharsetEncoder[] encoders; private final int priorityEncoderIndex; /** * Constructs an encoder set * * @param stringToEncode the string that needs to be encoded * @param priorityCharset The preferred {@link Charset} or null. * @param fnc1 fnc1 denotes the character in the input that represents the FNC1 character or -1 for a non-GS1 bar * code. When specified, it is considered an error to pass it as argument to the methods canEncode() or encode(). */ public ECIEncoderSet(String stringToEncode, Charset priorityCharset, int fnc1) { List<CharsetEncoder> neededEncoders = new ArrayList<>(); //we always need the ISO-8859-1 encoder. It is the default encoding neededEncoders.add(StandardCharsets.ISO_8859_1.newEncoder()); boolean needUnicodeEncoder = priorityCharset != null && priorityCharset.name().startsWith("UTF"); //Walk over the input string and see if all characters can be encoded with the list of encoders for (int i = 0; i < stringToEncode.length(); i++) { boolean canEncode = false; for (CharsetEncoder encoder : neededEncoders) { char c = stringToEncode.charAt(i); if (c == fnc1 || encoder.canEncode(c)) { canEncode = true; break; } } if (!canEncode) { //for the character at position i we don't yet have an encoder in the list for (CharsetEncoder encoder : ENCODERS) { if (encoder.canEncode(stringToEncode.charAt(i))) { //Good, we found an encoder that can encode the character. We add him to the list and continue scanning //the input neededEncoders.add(encoder); canEncode = true; break; } } } if (!canEncode) { //The character is not encodeable by any of the single byte encoders so we remember that we will need a //Unicode encoder. needUnicodeEncoder = true; } } if (neededEncoders.size() == 1 && !needUnicodeEncoder) { //the entire input can be encoded by the ISO-8859-1 encoder encoders = new CharsetEncoder[] { neededEncoders.get(0) }; } else { // we need more than one single byte encoder or we need a Unicode encoder. // In this case we append a UTF-8 and UTF-16 encoder to the list encoders = new CharsetEncoder[neededEncoders.size() + 2]; int index = 0; for (CharsetEncoder encoder : neededEncoders) { encoders[index++] = encoder; } encoders[index] = StandardCharsets.UTF_8.newEncoder(); encoders[index + 1] = StandardCharsets.UTF_16BE.newEncoder(); } //Compute priorityEncoderIndex by looking up priorityCharset in encoders int priorityEncoderIndexValue = -1; if (priorityCharset != null) { for (int i = 0; i < encoders.length; i++) { if (encoders[i] != null && priorityCharset.name().equals(encoders[i].charset().name())) { priorityEncoderIndexValue = i; break; } } } priorityEncoderIndex = priorityEncoderIndexValue; //invariants assert encoders[0].charset().equals(StandardCharsets.ISO_8859_1); } public int length() { return encoders.length; } public String getCharsetName(int index) { assert index < length(); return encoders[index].charset().name(); } public Charset getCharset(int index) { assert index < length(); return encoders[index].charset(); } public int getECIValue(int encoderIndex) { return CharacterSetECI.getCharacterSetECI(encoders[encoderIndex].charset()).getValue(); } /* * returns -1 if no priority charset was defined */ public int getPriorityEncoderIndex() { return priorityEncoderIndex; } public boolean canEncode(char c, int encoderIndex) {<FILL_FUNCTION_BODY>} public byte[] encode(char c, int encoderIndex) { assert encoderIndex < length(); CharsetEncoder encoder = encoders[encoderIndex]; assert encoder.canEncode("" + c); return ("" + c).getBytes(encoder.charset()); } public byte[] encode(String s, int encoderIndex) { assert encoderIndex < length(); CharsetEncoder encoder = encoders[encoderIndex]; return s.getBytes(encoder.charset()); } }
assert encoderIndex < length(); CharsetEncoder encoder = encoders[encoderIndex]; return encoder.canEncode("" + c);
1,699
40
1,739
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/common/ECIStringBuilder.java
ECIStringBuilder
encodeCurrentBytesIfAny
class ECIStringBuilder { private StringBuilder currentBytes; private StringBuilder result; private Charset currentCharset = StandardCharsets.ISO_8859_1; public ECIStringBuilder() { currentBytes = new StringBuilder(); } public ECIStringBuilder(int initialCapacity) { currentBytes = new StringBuilder(initialCapacity); } /** * Appends {@code value} as a byte value * * @param value character whose lowest byte is to be appended */ public void append(char value) { currentBytes.append((char) (value & 0xff)); } /** * Appends {@code value} as a byte value * * @param value byte to append */ public void append(byte value) { currentBytes.append((char) (value & 0xff)); } /** * Appends the characters in {@code value} as bytes values * * @param value string to append */ public void append(String value) { currentBytes.append(value); } /** * Append the string repesentation of {@code value} (short for {@code append(String.valueOf(value))}) * * @param value int to append as a string */ public void append(int value) { append(String.valueOf(value)); } /** * Appends ECI value to output. * * @param value ECI value to append, as an int * @throws FormatException on invalid ECI value */ public void appendECI(int value) throws FormatException { encodeCurrentBytesIfAny(); CharacterSetECI characterSetECI = CharacterSetECI.getCharacterSetECIByValue(value); if (characterSetECI == null) { throw FormatException.getFormatInstance(); } currentCharset = characterSetECI.getCharset(); } private void encodeCurrentBytesIfAny() {<FILL_FUNCTION_BODY>} /** * Appends the characters from {@code value} (unlike all other append methods of this class who append bytes) * * @param value characters to append */ public void appendCharacters(StringBuilder value) { encodeCurrentBytesIfAny(); result.append(value); } /** * Short for {@code toString().length()} (if possible, use {@link #isEmpty()} instead) * * @return length of string representation in characters */ public int length() { return toString().length(); } /** * @return true iff nothing has been appended */ public boolean isEmpty() { return currentBytes.length() == 0 && (result == null || result.length() == 0); } @Override public String toString() { encodeCurrentBytesIfAny(); return result == null ? "" : result.toString(); } }
if (currentCharset.equals(StandardCharsets.ISO_8859_1)) { if (currentBytes.length() > 0) { if (result == null) { result = currentBytes; currentBytes = new StringBuilder(); } else { result.append(currentBytes); currentBytes = new StringBuilder(); } } } else if (currentBytes.length() > 0) { byte[] bytes = currentBytes.toString().getBytes(StandardCharsets.ISO_8859_1); currentBytes = new StringBuilder(); if (result == null) { result = new StringBuilder(new String(bytes, currentCharset)); } else { result.append(new String(bytes, currentCharset)); } }
763
197
960
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/common/GlobalHistogramBinarizer.java
GlobalHistogramBinarizer
getBlackRow
class GlobalHistogramBinarizer extends Binarizer { private static final int LUMINANCE_BITS = 5; private static final int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS; private static final int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS; private static final byte[] EMPTY = new byte[0]; private byte[] luminances; private final int[] buckets; public GlobalHistogramBinarizer(LuminanceSource source) { super(source); luminances = EMPTY; buckets = new int[LUMINANCE_BUCKETS]; } // Applies simple sharpening to the row data to improve performance of the 1D Readers. @Override public BitArray getBlackRow(int y, BitArray row) throws NotFoundException {<FILL_FUNCTION_BODY>} // Does not sharpen the data, as this call is intended to only be used by 2D Readers. @Override public BitMatrix getBlackMatrix() throws NotFoundException { LuminanceSource source = getLuminanceSource(); int width = source.getWidth(); int height = source.getHeight(); BitMatrix matrix = new BitMatrix(width, height); // Quickly calculates the histogram by sampling four rows from the image. This proved to be // more robust on the blackbox tests than sampling a diagonal as we used to do. initArrays(width); int[] localBuckets = buckets; for (int y = 1; y < 5; y++) { int row = height * y / 5; byte[] localLuminances = source.getRow(row, luminances); int right = (width * 4) / 5; for (int x = width / 5; x < right; x++) { int pixel = localLuminances[x] & 0xff; localBuckets[pixel >> LUMINANCE_SHIFT]++; } } int blackPoint = estimateBlackPoint(localBuckets); // We delay reading the entire image luminance until the black point estimation succeeds. // Although we end up reading four rows twice, it is consistent with our motto of // "fail quickly" which is necessary for continuous scanning. byte[] localLuminances = source.getMatrix(); for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { int pixel = localLuminances[offset + x] & 0xff; if (pixel < blackPoint) { matrix.set(x, y); } } } return matrix; } @Override public Binarizer createBinarizer(LuminanceSource source) { return new GlobalHistogramBinarizer(source); } private void initArrays(int luminanceSize) { if (luminances.length < luminanceSize) { luminances = new byte[luminanceSize]; } for (int x = 0; x < LUMINANCE_BUCKETS; x++) { buckets[x] = 0; } } private static int estimateBlackPoint(int[] buckets) throws NotFoundException { // Find the tallest peak in the histogram. int numBuckets = buckets.length; int maxBucketCount = 0; int firstPeak = 0; int firstPeakSize = 0; for (int x = 0; x < numBuckets; x++) { if (buckets[x] > firstPeakSize) { firstPeak = x; firstPeakSize = buckets[x]; } if (buckets[x] > maxBucketCount) { maxBucketCount = buckets[x]; } } // Find the second-tallest peak which is somewhat far from the tallest peak. int secondPeak = 0; int secondPeakScore = 0; for (int x = 0; x < numBuckets; x++) { int distanceToBiggest = x - firstPeak; // Encourage more distant second peaks by multiplying by square of distance. int score = buckets[x] * distanceToBiggest * distanceToBiggest; if (score > secondPeakScore) { secondPeak = x; secondPeakScore = score; } } // Make sure firstPeak corresponds to the black peak. if (firstPeak > secondPeak) { int temp = firstPeak; firstPeak = secondPeak; secondPeak = temp; } // If there is too little contrast in the image to pick a meaningful black point, throw rather // than waste time trying to decode the image, and risk false positives. if (secondPeak - firstPeak <= numBuckets / 16) { throw NotFoundException.getNotFoundInstance(); } // Find a valley between them that is low and closer to the white peak. int bestValley = secondPeak - 1; int bestValleyScore = -1; for (int x = secondPeak - 1; x > firstPeak; x--) { int fromFirst = x - firstPeak; int score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]); if (score > bestValleyScore) { bestValley = x; bestValleyScore = score; } } return bestValley << LUMINANCE_SHIFT; } }
LuminanceSource source = getLuminanceSource(); int width = source.getWidth(); if (row == null || row.getSize() < width) { row = new BitArray(width); } else { row.clear(); } initArrays(width); byte[] localLuminances = source.getRow(y, luminances); int[] localBuckets = buckets; for (int x = 0; x < width; x++) { localBuckets[(localLuminances[x] & 0xff) >> LUMINANCE_SHIFT]++; } int blackPoint = estimateBlackPoint(localBuckets); if (width < 3) { // Special case for very small images for (int x = 0; x < width; x++) { if ((localLuminances[x] & 0xff) < blackPoint) { row.set(x); } } } else { int left = localLuminances[0] & 0xff; int center = localLuminances[1] & 0xff; for (int x = 1; x < width - 1; x++) { int right = localLuminances[x + 1] & 0xff; // A simple -1 4 -1 box filter with a weight of 2. if (((center * 4) - left - right) / 2 < blackPoint) { row.set(x); } left = center; center = right; } } return row;
1,448
405
1,853
<methods>public abstract com.google.zxing.Binarizer createBinarizer(com.google.zxing.LuminanceSource) ,public abstract com.google.zxing.common.BitMatrix getBlackMatrix() throws com.google.zxing.NotFoundException,public abstract com.google.zxing.common.BitArray getBlackRow(int, com.google.zxing.common.BitArray) throws com.google.zxing.NotFoundException,public final int getHeight() ,public final com.google.zxing.LuminanceSource getLuminanceSource() ,public final int getWidth() <variables>private final non-sealed com.google.zxing.LuminanceSource source
zxing_zxing
zxing/core/src/main/java/com/google/zxing/common/GridSampler.java
GridSampler
checkAndNudgePoints
class GridSampler { private static GridSampler gridSampler = new DefaultGridSampler(); /** * Sets the implementation of GridSampler used by the library. One global * instance is stored, which may sound problematic. But, the implementation provided * ought to be appropriate for the entire platform, and all uses of this library * in the whole lifetime of the JVM. For instance, an Android activity can swap in * an implementation that takes advantage of native platform libraries. * * @param newGridSampler The platform-specific object to install. */ public static void setGridSampler(GridSampler newGridSampler) { gridSampler = newGridSampler; } /** * @return the current implementation of GridSampler */ public static GridSampler getInstance() { return gridSampler; } /** * Samples an image for a rectangular matrix of bits of the given dimension. The sampling * transformation is determined by the coordinates of 4 points, in the original and transformed * image space. * * @param image image to sample * @param dimensionX width of {@link BitMatrix} to sample from image * @param dimensionY height of {@link BitMatrix} to sample from image * @param p1ToX point 1 preimage X * @param p1ToY point 1 preimage Y * @param p2ToX point 2 preimage X * @param p2ToY point 2 preimage Y * @param p3ToX point 3 preimage X * @param p3ToY point 3 preimage Y * @param p4ToX point 4 preimage X * @param p4ToY point 4 preimage Y * @param p1FromX point 1 image X * @param p1FromY point 1 image Y * @param p2FromX point 2 image X * @param p2FromY point 2 image Y * @param p3FromX point 3 image X * @param p3FromY point 3 image Y * @param p4FromX point 4 image X * @param p4FromY point 4 image Y * @return {@link BitMatrix} representing a grid of points sampled from the image within a region * defined by the "from" parameters * @throws NotFoundException if image can't be sampled, for example, if the transformation defined * by the given points is invalid or results in sampling outside the image boundaries */ public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY) throws NotFoundException; public abstract BitMatrix sampleGrid(BitMatrix image, int dimensionX, int dimensionY, PerspectiveTransform transform) throws NotFoundException; /** * <p>Checks a set of points that have been transformed to sample points on an image against * the image's dimensions to see if the point are even within the image.</p> * * <p>This method will actually "nudge" the endpoints back onto the image if they are found to be * barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder * patterns in an image where the QR Code runs all the way to the image border.</p> * * <p>For efficiency, the method will check points from either end of the line until one is found * to be within the image. Because the set of points are assumed to be linear, this is valid.</p> * * @param image image into which the points should map * @param points actual points in x1,y1,...,xn,yn form * @throws NotFoundException if an endpoint is lies outside the image boundaries */ protected static void checkAndNudgePoints(BitMatrix image, float[] points) throws NotFoundException {<FILL_FUNCTION_BODY>} }
int width = image.getWidth(); int height = image.getHeight(); // Check and nudge points from start until we see some that are OK: boolean nudged = true; int maxOffset = points.length - 1; // points.length must be even for (int offset = 0; offset < maxOffset && nudged; offset += 2) { int x = (int) points[offset]; int y = (int) points[offset + 1]; if (x < -1 || x > width || y < -1 || y > height) { throw NotFoundException.getNotFoundInstance(); } nudged = false; if (x == -1) { points[offset] = 0.0f; nudged = true; } else if (x == width) { points[offset] = width - 1; nudged = true; } if (y == -1) { points[offset + 1] = 0.0f; nudged = true; } else if (y == height) { points[offset + 1] = height - 1; nudged = true; } } // Check and nudge points from end: nudged = true; for (int offset = points.length - 2; offset >= 0 && nudged; offset -= 2) { int x = (int) points[offset]; int y = (int) points[offset + 1]; if (x < -1 || x > width || y < -1 || y > height) { throw NotFoundException.getNotFoundInstance(); } nudged = false; if (x == -1) { points[offset] = 0.0f; nudged = true; } else if (x == width) { points[offset] = width - 1; nudged = true; } if (y == -1) { points[offset + 1] = 0.0f; nudged = true; } else if (y == height) { points[offset + 1] = height - 1; nudged = true; } }
1,078
552
1,630
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/common/PerspectiveTransform.java
PerspectiveTransform
times
class PerspectiveTransform { private final float a11; private final float a12; private final float a13; private final float a21; private final float a22; private final float a23; private final float a31; private final float a32; private final float a33; private PerspectiveTransform(float a11, float a21, float a31, float a12, float a22, float a32, float a13, float a23, float a33) { this.a11 = a11; this.a12 = a12; this.a13 = a13; this.a21 = a21; this.a22 = a22; this.a23 = a23; this.a31 = a31; this.a32 = a32; this.a33 = a33; } public static PerspectiveTransform quadrilateralToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p, float x3p, float y3p) { PerspectiveTransform qToS = quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3); PerspectiveTransform sToQ = squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p); return sToQ.times(qToS); } public void transformPoints(float[] points) { float a11 = this.a11; float a12 = this.a12; float a13 = this.a13; float a21 = this.a21; float a22 = this.a22; float a23 = this.a23; float a31 = this.a31; float a32 = this.a32; float a33 = this.a33; int maxI = points.length - 1; // points.length must be even for (int i = 0; i < maxI; i += 2) { float x = points[i]; float y = points[i + 1]; float denominator = a13 * x + a23 * y + a33; points[i] = (a11 * x + a21 * y + a31) / denominator; points[i + 1] = (a12 * x + a22 * y + a32) / denominator; } } public void transformPoints(float[] xValues, float[] yValues) { int n = xValues.length; for (int i = 0; i < n; i++) { float x = xValues[i]; float y = yValues[i]; float denominator = a13 * x + a23 * y + a33; xValues[i] = (a11 * x + a21 * y + a31) / denominator; yValues[i] = (a12 * x + a22 * y + a32) / denominator; } } public static PerspectiveTransform squareToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) { float dx3 = x0 - x1 + x2 - x3; float dy3 = y0 - y1 + y2 - y3; if (dx3 == 0.0f && dy3 == 0.0f) { // Affine return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0f, 0.0f, 1.0f); } else { float dx1 = x1 - x2; float dx2 = x3 - x2; float dy1 = y1 - y2; float dy2 = y3 - y2; float denominator = dx1 * dy2 - dx2 * dy1; float a13 = (dx3 * dy2 - dx2 * dy3) / denominator; float a23 = (dx1 * dy3 - dx3 * dy1) / denominator; return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0f); } } public static PerspectiveTransform quadrilateralToSquare(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3) { // Here, the adjoint serves as the inverse: return squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint(); } PerspectiveTransform buildAdjoint() { // Adjoint is the transpose of the cofactor matrix: return new PerspectiveTransform(a22 * a33 - a23 * a32, a23 * a31 - a21 * a33, a21 * a32 - a22 * a31, a13 * a32 - a12 * a33, a11 * a33 - a13 * a31, a12 * a31 - a11 * a32, a12 * a23 - a13 * a22, a13 * a21 - a11 * a23, a11 * a22 - a12 * a21); } PerspectiveTransform times(PerspectiveTransform other) {<FILL_FUNCTION_BODY>} }
return new PerspectiveTransform(a11 * other.a11 + a21 * other.a12 + a31 * other.a13, a11 * other.a21 + a21 * other.a22 + a31 * other.a23, a11 * other.a31 + a21 * other.a32 + a31 * other.a33, a12 * other.a11 + a22 * other.a12 + a32 * other.a13, a12 * other.a21 + a22 * other.a22 + a32 * other.a23, a12 * other.a31 + a22 * other.a32 + a32 * other.a33, a13 * other.a11 + a23 * other.a12 + a33 * other.a13, a13 * other.a21 + a23 * other.a22 + a33 * other.a23, a13 * other.a31 + a23 * other.a32 + a33 * other.a33);
1,625
298
1,923
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/common/detector/MathUtils.java
MathUtils
distance
class MathUtils { private MathUtils() { } /** * Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its * argument to the nearest int, where x.5 rounds up to x+1. Semantics of this shortcut * differ slightly from {@link Math#round(float)} in that half rounds down for negative * values. -2.5 rounds to -3, not -2. For purposes here it makes no difference. * * @param d real value to round * @return nearest {@code int} */ public static int round(float d) { return (int) (d + (d < 0.0f ? -0.5f : 0.5f)); } /** * @param aX point A x coordinate * @param aY point A y coordinate * @param bX point B x coordinate * @param bY point B y coordinate * @return Euclidean distance between points A and B */ public static float distance(float aX, float aY, float bX, float bY) { double xDiff = aX - bX; double yDiff = aY - bY; return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff); } /** * @param aX point A x coordinate * @param aY point A y coordinate * @param bX point B x coordinate * @param bY point B y coordinate * @return Euclidean distance between points A and B */ public static float distance(int aX, int aY, int bX, int bY) {<FILL_FUNCTION_BODY>} /** * @param array values to sum * @return sum of values in array */ public static int sum(int[] array) { int count = 0; for (int a : array) { count += a; } return count; } }
double xDiff = aX - bX; double yDiff = aY - bY; return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
496
49
545
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/common/reedsolomon/GenericGF.java
GenericGF
buildMonomial
class GenericGF { public static final GenericGF AZTEC_DATA_12 = new GenericGF(0b1000001101001, 4096, 1); // x^12 + x^6 + x^5 + x^3 + 1 public static final GenericGF AZTEC_DATA_10 = new GenericGF(0b10000001001, 1024, 1); // x^10 + x^3 + 1 public static final GenericGF AZTEC_DATA_6 = new GenericGF(0b1000011, 64, 1); // x^6 + x + 1 public static final GenericGF AZTEC_PARAM = new GenericGF(0b10011, 16, 1); // x^4 + x + 1 public static final GenericGF QR_CODE_FIELD_256 = new GenericGF(0b100011101, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1 public static final GenericGF DATA_MATRIX_FIELD_256 = new GenericGF(0b100101101, 256, 1); // x^8 + x^5 + x^3 + x^2 + 1 public static final GenericGF AZTEC_DATA_8 = DATA_MATRIX_FIELD_256; public static final GenericGF MAXICODE_FIELD_64 = AZTEC_DATA_6; private final int[] expTable; private final int[] logTable; private final GenericGFPoly zero; private final GenericGFPoly one; private final int size; private final int primitive; private final int generatorBase; /** * Create a representation of GF(size) using the given primitive polynomial. * * @param primitive irreducible polynomial whose coefficients are represented by * the bits of an int, where the least-significant bit represents the constant * coefficient * @param size the size of the field * @param b the factor b in the generator polynomial can be 0- or 1-based * (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))). * In most cases it should be 1, but for QR code it is 0. */ public GenericGF(int primitive, int size, int b) { this.primitive = primitive; this.size = size; this.generatorBase = b; expTable = new int[size]; logTable = new int[size]; int x = 1; for (int i = 0; i < size; i++) { expTable[i] = x; x *= 2; // 2 (the polynomial x) is a primitive element if (x >= size) { x ^= primitive; x &= size - 1; } } for (int i = 0; i < size - 1; i++) { logTable[expTable[i]] = i; } // logTable[0] == 0 but this should never be used zero = new GenericGFPoly(this, new int[]{0}); one = new GenericGFPoly(this, new int[]{1}); } GenericGFPoly getZero() { return zero; } GenericGFPoly getOne() { return one; } /** * @return the monomial representing coefficient * x^degree */ GenericGFPoly buildMonomial(int degree, int coefficient) {<FILL_FUNCTION_BODY>} /** * Implements both addition and subtraction -- they are the same in GF(size). * * @return sum/difference of a and b */ static int addOrSubtract(int a, int b) { return a ^ b; } /** * @return 2 to the power of a in GF(size) */ int exp(int a) { return expTable[a]; } /** * @return base 2 log of a in GF(size) */ int log(int a) { if (a == 0) { throw new IllegalArgumentException(); } return logTable[a]; } /** * @return multiplicative inverse of a */ int inverse(int a) { if (a == 0) { throw new ArithmeticException(); } return expTable[size - logTable[a] - 1]; } /** * @return product of a and b in GF(size) */ int multiply(int a, int b) { if (a == 0 || b == 0) { return 0; } return expTable[(logTable[a] + logTable[b]) % (size - 1)]; } public int getSize() { return size; } public int getGeneratorBase() { return generatorBase; } @Override public String toString() { return "GF(0x" + Integer.toHexString(primitive) + ',' + size + ')'; } }
if (degree < 0) { throw new IllegalArgumentException(); } if (coefficient == 0) { return zero; } int[] coefficients = new int[degree + 1]; coefficients[0] = coefficient; return new GenericGFPoly(this, coefficients);
1,381
76
1,457
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/common/reedsolomon/ReedSolomonEncoder.java
ReedSolomonEncoder
buildGenerator
class ReedSolomonEncoder { private final GenericGF field; private final List<GenericGFPoly> cachedGenerators; public ReedSolomonEncoder(GenericGF field) { this.field = field; this.cachedGenerators = new ArrayList<>(); cachedGenerators.add(new GenericGFPoly(field, new int[]{1})); } private GenericGFPoly buildGenerator(int degree) {<FILL_FUNCTION_BODY>} public void encode(int[] toEncode, int ecBytes) { if (ecBytes == 0) { throw new IllegalArgumentException("No error correction bytes"); } int dataBytes = toEncode.length - ecBytes; if (dataBytes <= 0) { throw new IllegalArgumentException("No data bytes provided"); } GenericGFPoly generator = buildGenerator(ecBytes); int[] infoCoefficients = new int[dataBytes]; System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes); GenericGFPoly info = new GenericGFPoly(field, infoCoefficients); info = info.multiplyByMonomial(ecBytes, 1); GenericGFPoly remainder = info.divide(generator)[1]; int[] coefficients = remainder.getCoefficients(); int numZeroCoefficients = ecBytes - coefficients.length; for (int i = 0; i < numZeroCoefficients; i++) { toEncode[dataBytes + i] = 0; } System.arraycopy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.length); } }
if (degree >= cachedGenerators.size()) { GenericGFPoly lastGenerator = cachedGenerators.get(cachedGenerators.size() - 1); for (int d = cachedGenerators.size(); d <= degree; d++) { GenericGFPoly nextGenerator = lastGenerator.multiply( new GenericGFPoly(field, new int[] { 1, field.exp(d - 1 + field.getGeneratorBase()) })); cachedGenerators.add(nextGenerator); lastGenerator = nextGenerator; } } return cachedGenerators.get(degree);
428
152
580
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/DataMatrixReader.java
DataMatrixReader
extractPureBits
class DataMatrixReader implements Reader { private static final ResultPoint[] NO_POINTS = new ResultPoint[0]; private final Decoder decoder = new Decoder(); /** * Locates and decodes a Data Matrix code in an image. * * @return a String representing the content encoded by the Data Matrix code * @throws NotFoundException if a Data Matrix code cannot be found * @throws FormatException if a Data Matrix code cannot be decoded * @throws ChecksumException if error correction fails */ @Override public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); } @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { DecoderResult decoderResult; ResultPoint[] points; if (hints != null && hints.containsKey(DecodeHintType.PURE_BARCODE)) { BitMatrix bits = extractPureBits(image.getBlackMatrix()); decoderResult = decoder.decode(bits); points = NO_POINTS; } else { DetectorResult detectorResult = new Detector(image.getBlackMatrix()).detect(); decoderResult = decoder.decode(detectorResult.getBits()); points = detectorResult.getPoints(); } Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.DATA_MATRIX); List<byte[]> byteSegments = decoderResult.getByteSegments(); if (byteSegments != null) { result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments); } String ecLevel = decoderResult.getECLevel(); if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } result.putMetadata(ResultMetadataType.ERRORS_CORRECTED, decoderResult.getErrorsCorrected()); result.putMetadata(ResultMetadataType.SYMBOLOGY_IDENTIFIER, "]d" + decoderResult.getSymbologyModifier()); return result; } @Override public void reset() { // do nothing } /** * This method detects a code in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a code, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. */ private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException {<FILL_FUNCTION_BODY>} private static int moduleSize(int[] leftTopBlack, BitMatrix image) throws NotFoundException { int width = image.getWidth(); int x = leftTopBlack[0]; int y = leftTopBlack[1]; while (x < width && image.get(x, y)) { x++; } if (x == width) { throw NotFoundException.getNotFoundInstance(); } int moduleSize = x - leftTopBlack[0]; if (moduleSize == 0) { throw NotFoundException.getNotFoundInstance(); } return moduleSize; } }
int[] leftTopBlack = image.getTopLeftOnBit(); int[] rightBottomBlack = image.getBottomRightOnBit(); if (leftTopBlack == null || rightBottomBlack == null) { throw NotFoundException.getNotFoundInstance(); } int moduleSize = moduleSize(leftTopBlack, image); int top = leftTopBlack[1]; int bottom = rightBottomBlack[1]; int left = leftTopBlack[0]; int right = rightBottomBlack[0]; int matrixWidth = (right - left + 1) / moduleSize; int matrixHeight = (bottom - top + 1) / moduleSize; if (matrixWidth <= 0 || matrixHeight <= 0) { throw NotFoundException.getNotFoundInstance(); } // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = moduleSize / 2; top += nudge; left += nudge; // Now just read off the bits BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight); for (int y = 0; y < matrixHeight; y++) { int iOffset = top + y * moduleSize; for (int x = 0; x < matrixWidth; x++) { if (image.get(left + x * moduleSize, iOffset)) { bits.set(x, y); } } } return bits;
868
385
1,253
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/DataMatrixWriter.java
DataMatrixWriter
encode
class DataMatrixWriter implements Writer { @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) {<FILL_FUNCTION_BODY>} /** * Encode the given symbol info to a bit matrix. * * @param placement The DataMatrix placement. * @param symbolInfo The symbol info to encode. * @return The bit matrix generated. */ private static BitMatrix encodeLowLevel(DefaultPlacement placement, SymbolInfo symbolInfo, int width, int height) { int symbolWidth = symbolInfo.getSymbolDataWidth(); int symbolHeight = symbolInfo.getSymbolDataHeight(); ByteMatrix matrix = new ByteMatrix(symbolInfo.getSymbolWidth(), symbolInfo.getSymbolHeight()); int matrixY = 0; for (int y = 0; y < symbolHeight; y++) { // Fill the top edge with alternate 0 / 1 int matrixX; if ((y % symbolInfo.matrixHeight) == 0) { matrixX = 0; for (int x = 0; x < symbolInfo.getSymbolWidth(); x++) { matrix.set(matrixX, matrixY, (x % 2) == 0); matrixX++; } matrixY++; } matrixX = 0; for (int x = 0; x < symbolWidth; x++) { // Fill the right edge with full 1 if ((x % symbolInfo.matrixWidth) == 0) { matrix.set(matrixX, matrixY, true); matrixX++; } matrix.set(matrixX, matrixY, placement.getBit(x, y)); matrixX++; // Fill the right edge with alternate 0 / 1 if ((x % symbolInfo.matrixWidth) == symbolInfo.matrixWidth - 1) { matrix.set(matrixX, matrixY, (y % 2) == 0); matrixX++; } } matrixY++; // Fill the bottom edge with full 1 if ((y % symbolInfo.matrixHeight) == symbolInfo.matrixHeight - 1) { matrixX = 0; for (int x = 0; x < symbolInfo.getSymbolWidth(); x++) { matrix.set(matrixX, matrixY, true); matrixX++; } matrixY++; } } return convertByteMatrixToBitMatrix(matrix, width, height); } /** * Convert the ByteMatrix to BitMatrix. * * @param reqHeight The requested height of the image (in pixels) with the Datamatrix code * @param reqWidth The requested width of the image (in pixels) with the Datamatrix code * @param matrix The input matrix. * @return The output matrix. */ private static BitMatrix convertByteMatrixToBitMatrix(ByteMatrix matrix, int reqWidth, int reqHeight) { int matrixWidth = matrix.getWidth(); int matrixHeight = matrix.getHeight(); int outputWidth = Math.max(reqWidth, matrixWidth); int outputHeight = Math.max(reqHeight, matrixHeight); int multiple = Math.min(outputWidth / matrixWidth, outputHeight / matrixHeight); int leftPadding = (outputWidth - (matrixWidth * multiple)) / 2 ; int topPadding = (outputHeight - (matrixHeight * multiple)) / 2 ; BitMatrix output; // remove padding if requested width and height are too small if (reqHeight < matrixHeight || reqWidth < matrixWidth) { leftPadding = 0; topPadding = 0; output = new BitMatrix(matrixWidth, matrixHeight); } else { output = new BitMatrix(reqWidth, reqHeight); } output.clear(); for (int inputY = 0, outputY = topPadding; inputY < matrixHeight; inputY++, outputY += multiple) { // Write the contents of this row of the bytematrix for (int inputX = 0, outputX = leftPadding; inputX < matrixWidth; inputX++, outputX += multiple) { if (matrix.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; } }
if (contents.isEmpty()) { throw new IllegalArgumentException("Found empty contents"); } if (format != BarcodeFormat.DATA_MATRIX) { throw new IllegalArgumentException("Can only encode DATA_MATRIX, but got " + format); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions can't be negative: " + width + 'x' + height); } // Try to get force shape & min / max size SymbolShapeHint shape = SymbolShapeHint.FORCE_NONE; Dimension minSize = null; Dimension maxSize = null; if (hints != null) { SymbolShapeHint requestedShape = (SymbolShapeHint) hints.get(EncodeHintType.DATA_MATRIX_SHAPE); if (requestedShape != null) { shape = requestedShape; } @SuppressWarnings("deprecation") Dimension requestedMinSize = (Dimension) hints.get(EncodeHintType.MIN_SIZE); if (requestedMinSize != null) { minSize = requestedMinSize; } @SuppressWarnings("deprecation") Dimension requestedMaxSize = (Dimension) hints.get(EncodeHintType.MAX_SIZE); if (requestedMaxSize != null) { maxSize = requestedMaxSize; } } //1. step: Data encodation String encoded; boolean hasCompactionHint = hints != null && hints.containsKey(EncodeHintType.DATA_MATRIX_COMPACT) && Boolean.parseBoolean(hints.get(EncodeHintType.DATA_MATRIX_COMPACT).toString()); if (hasCompactionHint) { boolean hasGS1FormatHint = hints.containsKey(EncodeHintType.GS1_FORMAT) && Boolean.parseBoolean(hints.get(EncodeHintType.GS1_FORMAT).toString()); Charset charset = null; boolean hasEncodingHint = hints.containsKey(EncodeHintType.CHARACTER_SET); if (hasEncodingHint) { charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString()); } encoded = MinimalEncoder.encodeHighLevel(contents, charset, hasGS1FormatHint ? 0x1D : -1, shape); } else { boolean hasForceC40Hint = hints != null && hints.containsKey(EncodeHintType.FORCE_C40) && Boolean.parseBoolean(hints.get(EncodeHintType.FORCE_C40).toString()); encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize, hasForceC40Hint); } SymbolInfo symbolInfo = SymbolInfo.lookup(encoded.length(), shape, minSize, maxSize, true); //2. step: ECC generation String codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo); //3. step: Module placement in Matrix DefaultPlacement placement = new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight()); placement.place(); //4. step: low-level encoding return encodeLowLevel(placement, symbolInfo, width, height);
1,143
872
2,015
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/decoder/DataBlock.java
DataBlock
getDataBlocks
class DataBlock { private final int numDataCodewords; private final byte[] codewords; private DataBlock(int numDataCodewords, byte[] codewords) { this.numDataCodewords = numDataCodewords; this.codewords = codewords; } /** * <p>When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them. * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This * method will separate the data into original blocks.</p> * * @param rawCodewords bytes as read directly from the Data Matrix Code * @param version version of the Data Matrix Code * @return DataBlocks containing original bytes, "de-interleaved" from representation in the * Data Matrix Code */ static DataBlock[] getDataBlocks(byte[] rawCodewords, Version version) {<FILL_FUNCTION_BODY>} int getNumDataCodewords() { return numDataCodewords; } byte[] getCodewords() { return codewords; } }
// Figure out the number and size of data blocks used by this version Version.ECBlocks ecBlocks = version.getECBlocks(); // First count the total number of data blocks int totalBlocks = 0; Version.ECB[] ecBlockArray = ecBlocks.getECBlocks(); for (Version.ECB ecBlock : ecBlockArray) { totalBlocks += ecBlock.getCount(); } // Now establish DataBlocks of the appropriate size and number of data codewords DataBlock[] result = new DataBlock[totalBlocks]; int numResultBlocks = 0; for (Version.ECB ecBlock : ecBlockArray) { for (int i = 0; i < ecBlock.getCount(); i++) { int numDataCodewords = ecBlock.getDataCodewords(); int numBlockCodewords = ecBlocks.getECCodewords() + numDataCodewords; result[numResultBlocks++] = new DataBlock(numDataCodewords, new byte[numBlockCodewords]); } } // All blocks have the same amount of data, except that the last n // (where n may be 0) have 1 less byte. Figure out where these start. // TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144 int longerBlocksTotalCodewords = result[0].codewords.length; //int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1; int longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.getECCodewords(); int shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1; // The last elements of result may be 1 element shorter for 144 matrix // first fill out as many elements as all of them have minus 1 int rawCodewordsOffset = 0; for (int i = 0; i < shorterBlocksNumDataCodewords; i++) { for (int j = 0; j < numResultBlocks; j++) { result[j].codewords[i] = rawCodewords[rawCodewordsOffset++]; } } // Fill out the last data block in the longer ones boolean specialVersion = version.getVersionNumber() == 24; int numLongerBlocks = specialVersion ? 8 : numResultBlocks; for (int j = 0; j < numLongerBlocks; j++) { result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++]; } // Now add in error correction blocks int max = result[0].codewords.length; for (int i = longerBlocksNumDataCodewords; i < max; i++) { for (int j = 0; j < numResultBlocks; j++) { int jOffset = specialVersion ? (j + 8) % numResultBlocks : j; int iOffset = specialVersion && jOffset > 7 ? i - 1 : i; result[jOffset].codewords[iOffset] = rawCodewords[rawCodewordsOffset++]; } } if (rawCodewordsOffset != rawCodewords.length) { throw new IllegalArgumentException(); } return result;
291
822
1,113
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/decoder/Decoder.java
Decoder
decode
class Decoder { private final ReedSolomonDecoder rsDecoder; public Decoder() { rsDecoder = new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256); } /** * <p>Convenience method that can decode a Data Matrix Code represented as a 2D array of booleans. * "true" is taken to mean a black module.</p> * * @param image booleans representing white/black Data Matrix Code modules * @return text and bytes encoded within the Data Matrix Code * @throws FormatException if the Data Matrix Code cannot be decoded * @throws ChecksumException if error correction fails */ public DecoderResult decode(boolean[][] image) throws FormatException, ChecksumException { return decode(BitMatrix.parse(image)); } /** * <p>Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or "true" is taken * to mean a black module.</p> * * @param bits booleans representing white/black Data Matrix Code modules * @return text and bytes encoded within the Data Matrix Code * @throws FormatException if the Data Matrix Code cannot be decoded * @throws ChecksumException if error correction fails */ public DecoderResult decode(BitMatrix bits) throws FormatException, ChecksumException {<FILL_FUNCTION_BODY>} /** * <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to * correct the errors in-place using Reed-Solomon error correction.</p> * * @param codewordBytes data and error correction codewords * @param numDataCodewords number of codewords that are data bytes * @return the number of errors corrected * @throws ChecksumException if error correction fails */ private int correctErrors(byte[] codewordBytes, int numDataCodewords) throws ChecksumException { int numCodewords = codewordBytes.length; // First read into an array of ints int[] codewordsInts = new int[numCodewords]; for (int i = 0; i < numCodewords; i++) { codewordsInts[i] = codewordBytes[i] & 0xFF; } int errorsCorrected = 0; try { errorsCorrected = rsDecoder.decodeWithECCount(codewordsInts, codewordBytes.length - numDataCodewords); } catch (ReedSolomonException ignored) { throw ChecksumException.getChecksumInstance(); } // Copy back into array of bytes -- only need to worry about the bytes that were data // We don't care about errors in the error-correction codewords for (int i = 0; i < numDataCodewords; i++) { codewordBytes[i] = (byte) codewordsInts[i]; } return errorsCorrected; } }
// Construct a parser and read version, error-correction level BitMatrixParser parser = new BitMatrixParser(bits); Version version = parser.getVersion(); // Read codewords byte[] codewords = parser.readCodewords(); // Separate into data blocks DataBlock[] dataBlocks = DataBlock.getDataBlocks(codewords, version); // Count total number of data bytes int totalBytes = 0; for (DataBlock db : dataBlocks) { totalBytes += db.getNumDataCodewords(); } byte[] resultBytes = new byte[totalBytes]; int errorsCorrected = 0; int dataBlocksCount = dataBlocks.length; // Error-correct and copy data blocks together into a stream of bytes for (int j = 0; j < dataBlocksCount; j++) { DataBlock dataBlock = dataBlocks[j]; byte[] codewordBytes = dataBlock.getCodewords(); int numDataCodewords = dataBlock.getNumDataCodewords(); errorsCorrected += correctErrors(codewordBytes, numDataCodewords); for (int i = 0; i < numDataCodewords; i++) { // De-interlace data blocks. resultBytes[i * dataBlocksCount + j] = codewordBytes[i]; } } // Decode the contents of that stream of bytes DecoderResult result = DecodedBitStreamParser.decode(resultBytes); result.setErrorsCorrected(errorsCorrected); return result;
758
387
1,145
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/ASCIIEncoder.java
ASCIIEncoder
encodeASCIIDigits
class ASCIIEncoder implements Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.ASCII_ENCODATION; } @Override public void encode(EncoderContext context) { //step B int n = HighLevelEncoder.determineConsecutiveDigitCount(context.getMessage(), context.pos); if (n >= 2) { context.writeCodeword(encodeASCIIDigits(context.getMessage().charAt(context.pos), context.getMessage().charAt(context.pos + 1))); context.pos += 2; } else { char c = context.getCurrentChar(); int newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, getEncodingMode()); if (newMode != getEncodingMode()) { switch (newMode) { case HighLevelEncoder.BASE256_ENCODATION: context.writeCodeword(HighLevelEncoder.LATCH_TO_BASE256); context.signalEncoderChange(HighLevelEncoder.BASE256_ENCODATION); return; case HighLevelEncoder.C40_ENCODATION: context.writeCodeword(HighLevelEncoder.LATCH_TO_C40); context.signalEncoderChange(HighLevelEncoder.C40_ENCODATION); return; case HighLevelEncoder.X12_ENCODATION: context.writeCodeword(HighLevelEncoder.LATCH_TO_ANSIX12); context.signalEncoderChange(HighLevelEncoder.X12_ENCODATION); break; case HighLevelEncoder.TEXT_ENCODATION: context.writeCodeword(HighLevelEncoder.LATCH_TO_TEXT); context.signalEncoderChange(HighLevelEncoder.TEXT_ENCODATION); break; case HighLevelEncoder.EDIFACT_ENCODATION: context.writeCodeword(HighLevelEncoder.LATCH_TO_EDIFACT); context.signalEncoderChange(HighLevelEncoder.EDIFACT_ENCODATION); break; default: throw new IllegalStateException("Illegal mode: " + newMode); } } else if (HighLevelEncoder.isExtendedASCII(c)) { context.writeCodeword(HighLevelEncoder.UPPER_SHIFT); context.writeCodeword((char) (c - 128 + 1)); context.pos++; } else { context.writeCodeword((char) (c + 1)); context.pos++; } } } private static char encodeASCIIDigits(char digit1, char digit2) {<FILL_FUNCTION_BODY>} }
if (HighLevelEncoder.isDigit(digit1) && HighLevelEncoder.isDigit(digit2)) { int num = (digit1 - 48) * 10 + (digit2 - 48); return (char) (num + 130); } throw new IllegalArgumentException("not digits: " + digit1 + digit2);
715
98
813
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/Base256Encoder.java
Base256Encoder
encode
class Base256Encoder implements Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.BASE256_ENCODATION; } @Override public void encode(EncoderContext context) {<FILL_FUNCTION_BODY>} private static char randomize255State(char ch, int codewordPosition) { int pseudoRandom = ((149 * codewordPosition) % 255) + 1; int tempVariable = ch + pseudoRandom; if (tempVariable <= 255) { return (char) tempVariable; } else { return (char) (tempVariable - 256); } } }
StringBuilder buffer = new StringBuilder(); buffer.append('\0'); //Initialize length field while (context.hasMoreCharacters()) { char c = context.getCurrentChar(); buffer.append(c); context.pos++; int newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, getEncodingMode()); if (newMode != getEncodingMode()) { // Return to ASCII encodation, which will actually handle latch to new mode context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); break; } } int dataCount = buffer.length() - 1; int lengthFieldSize = 1; int currentSize = context.getCodewordCount() + dataCount + lengthFieldSize; context.updateSymbolInfo(currentSize); boolean mustPad = (context.getSymbolInfo().getDataCapacity() - currentSize) > 0; if (context.hasMoreCharacters() || mustPad) { if (dataCount <= 249) { buffer.setCharAt(0, (char) dataCount); } else if (dataCount <= 1555) { buffer.setCharAt(0, (char) ((dataCount / 250) + 249)); buffer.insert(1, (char) (dataCount % 250)); } else { throw new IllegalStateException( "Message length not in valid ranges: " + dataCount); } } for (int i = 0, c = buffer.length(); i < c; i++) { context.writeCodeword(randomize255State( buffer.charAt(i), context.getCodewordCount() + 1)); }
183
441
624
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/C40Encoder.java
C40Encoder
encodeChar
class C40Encoder implements Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.C40_ENCODATION; } void encodeMaximal(EncoderContext context) { StringBuilder buffer = new StringBuilder(); int lastCharSize = 0; int backtrackStartPosition = context.pos; int backtrackBufferLength = 0; while (context.hasMoreCharacters()) { char c = context.getCurrentChar(); context.pos++; lastCharSize = encodeChar(c, buffer); if (buffer.length() % 3 == 0) { backtrackStartPosition = context.pos; backtrackBufferLength = buffer.length(); } } if (backtrackBufferLength != buffer.length()) { int unwritten = (buffer.length() / 3) * 2; int curCodewordCount = context.getCodewordCount() + unwritten + 1; // +1 for the latch to C40 context.updateSymbolInfo(curCodewordCount); int available = context.getSymbolInfo().getDataCapacity() - curCodewordCount; int rest = buffer.length() % 3; if ((rest == 2 && available != 2) || (rest == 1 && (lastCharSize > 3 || available != 1))) { buffer.setLength(backtrackBufferLength); context.pos = backtrackStartPosition; } } if (buffer.length() > 0) { context.writeCodeword(HighLevelEncoder.LATCH_TO_C40); } handleEOD(context, buffer); } @Override public void encode(EncoderContext context) { //step C StringBuilder buffer = new StringBuilder(); while (context.hasMoreCharacters()) { char c = context.getCurrentChar(); context.pos++; int lastCharSize = encodeChar(c, buffer); int unwritten = (buffer.length() / 3) * 2; int curCodewordCount = context.getCodewordCount() + unwritten; context.updateSymbolInfo(curCodewordCount); int available = context.getSymbolInfo().getDataCapacity() - curCodewordCount; if (!context.hasMoreCharacters()) { //Avoid having a single C40 value in the last triplet StringBuilder removed = new StringBuilder(); if ((buffer.length() % 3) == 2 && available != 2) { lastCharSize = backtrackOneCharacter(context, buffer, removed, lastCharSize); } while ((buffer.length() % 3) == 1 && (lastCharSize > 3 || available != 1)) { lastCharSize = backtrackOneCharacter(context, buffer, removed, lastCharSize); } break; } int count = buffer.length(); if ((count % 3) == 0) { int newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, getEncodingMode()); if (newMode != getEncodingMode()) { // Return to ASCII encodation, which will actually handle latch to new mode context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); break; } } } handleEOD(context, buffer); } private int backtrackOneCharacter(EncoderContext context, StringBuilder buffer, StringBuilder removed, int lastCharSize) { int count = buffer.length(); buffer.delete(count - lastCharSize, count); context.pos--; char c = context.getCurrentChar(); lastCharSize = encodeChar(c, removed); context.resetSymbolInfo(); //Deal with possible reduction in symbol size return lastCharSize; } static void writeNextTriplet(EncoderContext context, StringBuilder buffer) { context.writeCodewords(encodeToCodewords(buffer)); buffer.delete(0, 3); } /** * Handle "end of data" situations * * @param context the encoder context * @param buffer the buffer with the remaining encoded characters */ void handleEOD(EncoderContext context, StringBuilder buffer) { int unwritten = (buffer.length() / 3) * 2; int rest = buffer.length() % 3; int curCodewordCount = context.getCodewordCount() + unwritten; context.updateSymbolInfo(curCodewordCount); int available = context.getSymbolInfo().getDataCapacity() - curCodewordCount; if (rest == 2) { buffer.append('\0'); //Shift 1 while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } } else if (available == 1 && rest == 1) { while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } // else no unlatch context.pos--; } else if (rest == 0) { while (buffer.length() >= 3) { writeNextTriplet(context, buffer); } if (available > 0 || context.hasMoreCharacters()) { context.writeCodeword(HighLevelEncoder.C40_UNLATCH); } } else { throw new IllegalStateException("Unexpected case. Please report!"); } context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); } int encodeChar(char c, StringBuilder sb) {<FILL_FUNCTION_BODY>} private static String encodeToCodewords(CharSequence sb) { int v = (1600 * sb.charAt(0)) + (40 * sb.charAt(1)) + sb.charAt(2) + 1; char cw1 = (char) (v / 256); char cw2 = (char) (v % 256); return new String(new char[] {cw1, cw2}); } }
if (c == ' ') { sb.append('\3'); return 1; } if (c >= '0' && c <= '9') { sb.append((char) (c - 48 + 4)); return 1; } if (c >= 'A' && c <= 'Z') { sb.append((char) (c - 65 + 14)); return 1; } if (c < ' ') { sb.append('\0'); //Shift 1 Set sb.append(c); return 2; } if (c <= '/') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 33)); return 2; } if (c <= '@') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 58 + 15)); return 2; } if (c <= '_') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 91 + 22)); return 2; } if (c <= 127) { sb.append('\2'); //Shift 3 Set sb.append((char) (c - 96)); return 2; } sb.append("\1\u001e"); //Shift 2, Upper Shift int len = 2; len += encodeChar((char) (c - 128), sb); return len;
1,606
407
2,013
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/DefaultPlacement.java
DefaultPlacement
module
class DefaultPlacement { private final CharSequence codewords; private final int numrows; private final int numcols; private final byte[] bits; /** * Main constructor * * @param codewords the codewords to place * @param numcols the number of columns * @param numrows the number of rows */ public DefaultPlacement(CharSequence codewords, int numcols, int numrows) { this.codewords = codewords; this.numcols = numcols; this.numrows = numrows; this.bits = new byte[numcols * numrows]; Arrays.fill(this.bits, (byte) -1); //Initialize with "not set" value } final int getNumrows() { return numrows; } final int getNumcols() { return numcols; } final byte[] getBits() { return bits; } public final boolean getBit(int col, int row) { return bits[row * numcols + col] == 1; } private void setBit(int col, int row, boolean bit) { bits[row * numcols + col] = (byte) (bit ? 1 : 0); } private boolean noBit(int col, int row) { return bits[row * numcols + col] < 0; } public final void place() { int pos = 0; int row = 4; int col = 0; do { // repeatedly first check for one of the special corner cases, then... if ((row == numrows) && (col == 0)) { corner1(pos++); } if ((row == numrows - 2) && (col == 0) && ((numcols % 4) != 0)) { corner2(pos++); } if ((row == numrows - 2) && (col == 0) && (numcols % 8 == 4)) { corner3(pos++); } if ((row == numrows + 4) && (col == 2) && ((numcols % 8) == 0)) { corner4(pos++); } // sweep upward diagonally, inserting successive characters... do { if ((row < numrows) && (col >= 0) && noBit(col, row)) { utah(row, col, pos++); } row -= 2; col += 2; } while (row >= 0 && (col < numcols)); row++; col += 3; // and then sweep downward diagonally, inserting successive characters, ... do { if ((row >= 0) && (col < numcols) && noBit(col, row)) { utah(row, col, pos++); } row += 2; col -= 2; } while ((row < numrows) && (col >= 0)); row += 3; col++; // ...until the entire array is scanned } while ((row < numrows) || (col < numcols)); // Lastly, if the lower right-hand corner is untouched, fill in fixed pattern if (noBit(numcols - 1, numrows - 1)) { setBit(numcols - 1, numrows - 1, true); setBit(numcols - 2, numrows - 2, true); } } private void module(int row, int col, int pos, int bit) {<FILL_FUNCTION_BODY>} /** * Places the 8 bits of a utah-shaped symbol character in ECC200. * * @param row the row * @param col the column * @param pos character position */ private void utah(int row, int col, int pos) { module(row - 2, col - 2, pos, 1); module(row - 2, col - 1, pos, 2); module(row - 1, col - 2, pos, 3); module(row - 1, col - 1, pos, 4); module(row - 1, col, pos, 5); module(row, col - 2, pos, 6); module(row, col - 1, pos, 7); module(row, col, pos, 8); } private void corner1(int pos) { module(numrows - 1, 0, pos, 1); module(numrows - 1, 1, pos, 2); module(numrows - 1, 2, pos, 3); module(0, numcols - 2, pos, 4); module(0, numcols - 1, pos, 5); module(1, numcols - 1, pos, 6); module(2, numcols - 1, pos, 7); module(3, numcols - 1, pos, 8); } private void corner2(int pos) { module(numrows - 3, 0, pos, 1); module(numrows - 2, 0, pos, 2); module(numrows - 1, 0, pos, 3); module(0, numcols - 4, pos, 4); module(0, numcols - 3, pos, 5); module(0, numcols - 2, pos, 6); module(0, numcols - 1, pos, 7); module(1, numcols - 1, pos, 8); } private void corner3(int pos) { module(numrows - 3, 0, pos, 1); module(numrows - 2, 0, pos, 2); module(numrows - 1, 0, pos, 3); module(0, numcols - 2, pos, 4); module(0, numcols - 1, pos, 5); module(1, numcols - 1, pos, 6); module(2, numcols - 1, pos, 7); module(3, numcols - 1, pos, 8); } private void corner4(int pos) { module(numrows - 1, 0, pos, 1); module(numrows - 1, numcols - 1, pos, 2); module(0, numcols - 3, pos, 3); module(0, numcols - 2, pos, 4); module(0, numcols - 1, pos, 5); module(1, numcols - 3, pos, 6); module(1, numcols - 2, pos, 7); module(1, numcols - 1, pos, 8); } }
if (row < 0) { row += numrows; col += 4 - ((numrows + 4) % 8); } if (col < 0) { col += numcols; row += 4 - ((numcols + 4) % 8); } // Note the conversion: int v = codewords.charAt(pos); v &= 1 << (8 - bit); setBit(col, row, v != 0);
1,781
121
1,902
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/EdifactEncoder.java
EdifactEncoder
handleEOD
class EdifactEncoder implements Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.EDIFACT_ENCODATION; } @Override public void encode(EncoderContext context) { //step F StringBuilder buffer = new StringBuilder(); while (context.hasMoreCharacters()) { char c = context.getCurrentChar(); encodeChar(c, buffer); context.pos++; int count = buffer.length(); if (count >= 4) { context.writeCodewords(encodeToCodewords(buffer)); buffer.delete(0, 4); int newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, getEncodingMode()); if (newMode != getEncodingMode()) { // Return to ASCII encodation, which will actually handle latch to new mode context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); break; } } } buffer.append((char) 31); //Unlatch handleEOD(context, buffer); } /** * Handle "end of data" situations * * @param context the encoder context * @param buffer the buffer with the remaining encoded characters */ private static void handleEOD(EncoderContext context, CharSequence buffer) {<FILL_FUNCTION_BODY>} private static void encodeChar(char c, StringBuilder sb) { if (c >= ' ' && c <= '?') { sb.append(c); } else if (c >= '@' && c <= '^') { sb.append((char) (c - 64)); } else { HighLevelEncoder.illegalCharacter(c); } } private static String encodeToCodewords(CharSequence sb) { int len = sb.length(); if (len == 0) { throw new IllegalStateException("StringBuilder must not be empty"); } char c1 = sb.charAt(0); char c2 = len >= 2 ? sb.charAt(1) : 0; char c3 = len >= 3 ? sb.charAt(2) : 0; char c4 = len >= 4 ? sb.charAt(3) : 0; int v = (c1 << 18) + (c2 << 12) + (c3 << 6) + c4; char cw1 = (char) ((v >> 16) & 255); char cw2 = (char) ((v >> 8) & 255); char cw3 = (char) (v & 255); StringBuilder res = new StringBuilder(3); res.append(cw1); if (len >= 2) { res.append(cw2); } if (len >= 3) { res.append(cw3); } return res.toString(); } }
try { int count = buffer.length(); if (count == 0) { return; //Already finished } if (count == 1) { //Only an unlatch at the end context.updateSymbolInfo(); int available = context.getSymbolInfo().getDataCapacity() - context.getCodewordCount(); int remaining = context.getRemainingCharacters(); // The following two lines are a hack inspired by the 'fix' from https://sourceforge.net/p/barcode4j/svn/221/ if (remaining > available) { context.updateSymbolInfo(context.getCodewordCount() + 1); available = context.getSymbolInfo().getDataCapacity() - context.getCodewordCount(); } if (remaining <= available && available <= 2) { return; //No unlatch } } if (count > 4) { throw new IllegalStateException("Count must not exceed 4"); } int restChars = count - 1; String encoded = encodeToCodewords(buffer); boolean endOfSymbolReached = !context.hasMoreCharacters(); boolean restInAscii = endOfSymbolReached && restChars <= 2; if (restChars <= 2) { context.updateSymbolInfo(context.getCodewordCount() + restChars); int available = context.getSymbolInfo().getDataCapacity() - context.getCodewordCount(); if (available >= 3) { restInAscii = false; context.updateSymbolInfo(context.getCodewordCount() + encoded.length()); //available = context.symbolInfo.dataCapacity - context.getCodewordCount(); } } if (restInAscii) { context.resetSymbolInfo(); context.pos -= restChars; } else { context.writeCodewords(encoded); } } finally { context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); }
761
516
1,277
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/EncoderContext.java
EncoderContext
updateSymbolInfo
class EncoderContext { private final String msg; private SymbolShapeHint shape; private Dimension minSize; private Dimension maxSize; private final StringBuilder codewords; int pos; private int newEncoding; private SymbolInfo symbolInfo; private int skipAtEnd; EncoderContext(String msg) { //From this point on Strings are not Unicode anymore! byte[] msgBinary = msg.getBytes(StandardCharsets.ISO_8859_1); StringBuilder sb = new StringBuilder(msgBinary.length); for (int i = 0, c = msgBinary.length; i < c; i++) { char ch = (char) (msgBinary[i] & 0xff); if (ch == '?' && msg.charAt(i) != '?') { throw new IllegalArgumentException("Message contains characters outside ISO-8859-1 encoding."); } sb.append(ch); } this.msg = sb.toString(); //Not Unicode here! shape = SymbolShapeHint.FORCE_NONE; this.codewords = new StringBuilder(msg.length()); newEncoding = -1; } public void setSymbolShape(SymbolShapeHint shape) { this.shape = shape; } public void setSizeConstraints(Dimension minSize, Dimension maxSize) { this.minSize = minSize; this.maxSize = maxSize; } public String getMessage() { return this.msg; } public void setSkipAtEnd(int count) { this.skipAtEnd = count; } public char getCurrentChar() { return msg.charAt(pos); } public char getCurrent() { return msg.charAt(pos); } public StringBuilder getCodewords() { return codewords; } public void writeCodewords(String codewords) { this.codewords.append(codewords); } public void writeCodeword(char codeword) { this.codewords.append(codeword); } public int getCodewordCount() { return this.codewords.length(); } public int getNewEncoding() { return newEncoding; } public void signalEncoderChange(int encoding) { this.newEncoding = encoding; } public void resetEncoderSignal() { this.newEncoding = -1; } public boolean hasMoreCharacters() { return pos < getTotalMessageCharCount(); } private int getTotalMessageCharCount() { return msg.length() - skipAtEnd; } public int getRemainingCharacters() { return getTotalMessageCharCount() - pos; } public SymbolInfo getSymbolInfo() { return symbolInfo; } public void updateSymbolInfo() { updateSymbolInfo(getCodewordCount()); } public void updateSymbolInfo(int len) {<FILL_FUNCTION_BODY>} public void resetSymbolInfo() { this.symbolInfo = null; } }
if (this.symbolInfo == null || len > this.symbolInfo.getDataCapacity()) { this.symbolInfo = SymbolInfo.lookup(len, shape, minSize, maxSize, true); }
806
55
861
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/TextEncoder.java
TextEncoder
encodeChar
class TextEncoder extends C40Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.TEXT_ENCODATION; } @Override int encodeChar(char c, StringBuilder sb) {<FILL_FUNCTION_BODY>} }
if (c == ' ') { sb.append('\3'); return 1; } if (c >= '0' && c <= '9') { sb.append((char) (c - 48 + 4)); return 1; } if (c >= 'a' && c <= 'z') { sb.append((char) (c - 97 + 14)); return 1; } if (c < ' ') { sb.append('\0'); //Shift 1 Set sb.append(c); return 2; } if (c <= '/') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 33)); return 2; } if (c <= '@') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 58 + 15)); return 2; } if (c >= '[' && c <= '_') { sb.append('\1'); //Shift 2 Set sb.append((char) (c - 91 + 22)); return 2; } if (c == '`') { sb.append('\2'); //Shift 3 Set sb.append((char) 0); // '`' - 96 == 0 return 2; } if (c <= 'Z') { sb.append('\2'); //Shift 3 Set sb.append((char) (c - 65 + 1)); return 2; } if (c <= 127) { sb.append('\2'); //Shift 3 Set sb.append((char) (c - 123 + 27)); return 2; } sb.append("\1\u001e"); //Shift 2, Upper Shift int len = 2; len += encodeChar((char) (c - 128), sb); return len;
78
520
598
<methods>public void encode(com.google.zxing.datamatrix.encoder.EncoderContext) ,public int getEncodingMode() <variables>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/datamatrix/encoder/X12Encoder.java
X12Encoder
encodeChar
class X12Encoder extends C40Encoder { @Override public int getEncodingMode() { return HighLevelEncoder.X12_ENCODATION; } @Override public void encode(EncoderContext context) { //step C StringBuilder buffer = new StringBuilder(); while (context.hasMoreCharacters()) { char c = context.getCurrentChar(); context.pos++; encodeChar(c, buffer); int count = buffer.length(); if ((count % 3) == 0) { writeNextTriplet(context, buffer); int newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, getEncodingMode()); if (newMode != getEncodingMode()) { // Return to ASCII encodation, which will actually handle latch to new mode context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); break; } } } handleEOD(context, buffer); } @Override int encodeChar(char c, StringBuilder sb) {<FILL_FUNCTION_BODY>} @Override void handleEOD(EncoderContext context, StringBuilder buffer) { context.updateSymbolInfo(); int available = context.getSymbolInfo().getDataCapacity() - context.getCodewordCount(); int count = buffer.length(); context.pos -= count; if (context.getRemainingCharacters() > 1 || available > 1 || context.getRemainingCharacters() != available) { context.writeCodeword(HighLevelEncoder.X12_UNLATCH); } if (context.getNewEncoding() < 0) { context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); } } }
switch (c) { case '\r': sb.append('\0'); break; case '*': sb.append('\1'); break; case '>': sb.append('\2'); break; case ' ': sb.append('\3'); break; default: if (c >= '0' && c <= '9') { sb.append((char) (c - 48 + 4)); } else if (c >= 'A' && c <= 'Z') { sb.append((char) (c - 65 + 14)); } else { HighLevelEncoder.illegalCharacter(c); } break; } return 1;
472
192
664
<methods>public void encode(com.google.zxing.datamatrix.encoder.EncoderContext) ,public int getEncodingMode() <variables>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/maxicode/MaxiCodeReader.java
MaxiCodeReader
extractPureBits
class MaxiCodeReader implements Reader { private static final ResultPoint[] NO_POINTS = new ResultPoint[0]; private static final int MATRIX_WIDTH = 30; private static final int MATRIX_HEIGHT = 33; private final Decoder decoder = new Decoder(); /** * Locates and decodes a MaxiCode in an image. * * @return a String representing the content encoded by the MaxiCode * @throws NotFoundException if a MaxiCode cannot be found * @throws FormatException if a MaxiCode cannot be decoded * @throws ChecksumException if error correction fails */ @Override public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); } @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { // Note that MaxiCode reader effectively always assumes PURE_BARCODE mode // and can't detect it in an image BitMatrix bits = extractPureBits(image.getBlackMatrix()); DecoderResult decoderResult = decoder.decode(bits, hints); Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), NO_POINTS, BarcodeFormat.MAXICODE); result.putMetadata(ResultMetadataType.ERRORS_CORRECTED, decoderResult.getErrorsCorrected()); String ecLevel = decoderResult.getECLevel(); if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } return result; } @Override public void reset() { // do nothing } /** * This method detects a code in a "pure" image -- that is, pure monochrome image * which contains only an unrotated, unskewed, image of a code, with some white border * around it. This is a specialized method that works exceptionally fast in this special * case. */ private static BitMatrix extractPureBits(BitMatrix image) throws NotFoundException {<FILL_FUNCTION_BODY>} }
int[] enclosingRectangle = image.getEnclosingRectangle(); if (enclosingRectangle == null) { throw NotFoundException.getNotFoundInstance(); } int left = enclosingRectangle[0]; int top = enclosingRectangle[1]; int width = enclosingRectangle[2]; int height = enclosingRectangle[3]; // Now just read off the bits BitMatrix bits = new BitMatrix(MATRIX_WIDTH, MATRIX_HEIGHT); for (int y = 0; y < MATRIX_HEIGHT; y++) { int iy = top + Math.min((y * height + height / 2) / MATRIX_HEIGHT, height - 1); for (int x = 0; x < MATRIX_WIDTH; x++) { // srowen: I don't quite understand why the formula below is necessary, but it // can walk off the image if left + width = the right boundary. So cap it. int ix = left + Math.min( (x * width + width / 2 + (y & 0x01) * width / 2) / MATRIX_WIDTH, width - 1); if (image.get(ix, iy)) { bits.set(x, y); } } } return bits;
579
356
935
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/maxicode/decoder/Decoder.java
Decoder
correctErrors
class Decoder { private static final int ALL = 0; private static final int EVEN = 1; private static final int ODD = 2; private final ReedSolomonDecoder rsDecoder; public Decoder() { rsDecoder = new ReedSolomonDecoder(GenericGF.MAXICODE_FIELD_64); } public DecoderResult decode(BitMatrix bits) throws ChecksumException, FormatException { return decode(bits, null); } public DecoderResult decode(BitMatrix bits, Map<DecodeHintType,?> hints) throws FormatException, ChecksumException { BitMatrixParser parser = new BitMatrixParser(bits); byte[] codewords = parser.readCodewords(); int errorsCorrected = correctErrors(codewords, 0, 10, 10, ALL); int mode = codewords[0] & 0x0F; byte[] datawords; switch (mode) { case 2: case 3: case 4: errorsCorrected += correctErrors(codewords, 20, 84, 40, EVEN); errorsCorrected += correctErrors(codewords, 20, 84, 40, ODD); datawords = new byte[94]; break; case 5: errorsCorrected += correctErrors(codewords, 20, 68, 56, EVEN); errorsCorrected += correctErrors(codewords, 20, 68, 56, ODD); datawords = new byte[78]; break; default: throw FormatException.getFormatInstance(); } System.arraycopy(codewords, 0, datawords, 0, 10); System.arraycopy(codewords, 20, datawords, 10, datawords.length - 10); DecoderResult result = DecodedBitStreamParser.decode(datawords, mode); result.setErrorsCorrected(errorsCorrected); return result; } private int correctErrors(byte[] codewordBytes, int start, int dataCodewords, int ecCodewords, int mode) throws ChecksumException {<FILL_FUNCTION_BODY>} }
int codewords = dataCodewords + ecCodewords; // in EVEN or ODD mode only half the codewords int divisor = mode == ALL ? 1 : 2; // First read into an array of ints int[] codewordsInts = new int[codewords / divisor]; for (int i = 0; i < codewords; i++) { if ((mode == ALL) || (i % 2 == (mode - 1))) { codewordsInts[i / divisor] = codewordBytes[i + start] & 0xFF; } } int errorsCorrected = 0; try { errorsCorrected = rsDecoder.decodeWithECCount(codewordsInts, ecCodewords / divisor); } catch (ReedSolomonException ignored) { throw ChecksumException.getChecksumInstance(); } // Copy back into array of bytes -- only need to worry about the bytes that were data // We don't care about errors in the error-correction codewords for (int i = 0; i < dataCodewords; i++) { if ((mode == ALL) || (i % 2 == (mode - 1))) { codewordBytes[i + start] = (byte) codewordsInts[i / divisor]; } } return errorsCorrected;
592
343
935
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/multi/ByQuadrantReader.java
ByQuadrantReader
decode
class ByQuadrantReader implements Reader { private final Reader delegate; public ByQuadrantReader(Reader delegate) { this.delegate = delegate; } @Override public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException { return decode(image, null); } @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException {<FILL_FUNCTION_BODY>} @Override public void reset() { delegate.reset(); } private static void makeAbsolute(ResultPoint[] points, int leftOffset, int topOffset) { if (points != null) { for (int i = 0; i < points.length; i++) { ResultPoint relative = points[i]; if (relative != null) { points[i] = new ResultPoint(relative.getX() + leftOffset, relative.getY() + topOffset); } } } } }
int width = image.getWidth(); int height = image.getHeight(); int halfWidth = width / 2; int halfHeight = height / 2; try { // No need to call makeAbsolute as results will be relative to original top left here return delegate.decode(image.crop(0, 0, halfWidth, halfHeight), hints); } catch (NotFoundException re) { // continue } try { Result result = delegate.decode(image.crop(halfWidth, 0, halfWidth, halfHeight), hints); makeAbsolute(result.getResultPoints(), halfWidth, 0); return result; } catch (NotFoundException re) { // continue } try { Result result = delegate.decode(image.crop(0, halfHeight, halfWidth, halfHeight), hints); makeAbsolute(result.getResultPoints(), 0, halfHeight); return result; } catch (NotFoundException re) { // continue } try { Result result = delegate.decode(image.crop(halfWidth, halfHeight, halfWidth, halfHeight), hints); makeAbsolute(result.getResultPoints(), halfWidth, halfHeight); return result; } catch (NotFoundException re) { // continue } int quarterWidth = halfWidth / 2; int quarterHeight = halfHeight / 2; BinaryBitmap center = image.crop(quarterWidth, quarterHeight, halfWidth, halfHeight); Result result = delegate.decode(center, hints); makeAbsolute(result.getResultPoints(), quarterWidth, quarterHeight); return result;
285
418
703
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/multi/GenericMultipleBarcodeReader.java
GenericMultipleBarcodeReader
doDecodeMultiple
class GenericMultipleBarcodeReader implements MultipleBarcodeReader { private static final int MIN_DIMENSION_TO_RECUR = 100; private static final int MAX_DEPTH = 4; static final Result[] EMPTY_RESULT_ARRAY = new Result[0]; private final Reader delegate; public GenericMultipleBarcodeReader(Reader delegate) { this.delegate = delegate; } @Override public Result[] decodeMultiple(BinaryBitmap image) throws NotFoundException { return decodeMultiple(image, null); } @Override public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException { List<Result> results = new ArrayList<>(); doDecodeMultiple(image, hints, results, 0, 0, 0); if (results.isEmpty()) { throw NotFoundException.getNotFoundInstance(); } return results.toArray(EMPTY_RESULT_ARRAY); } private void doDecodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints, List<Result> results, int xOffset, int yOffset, int currentDepth) {<FILL_FUNCTION_BODY>} private static Result translateResultPoints(Result result, int xOffset, int yOffset) { ResultPoint[] oldResultPoints = result.getResultPoints(); if (oldResultPoints == null) { return result; } ResultPoint[] newResultPoints = new ResultPoint[oldResultPoints.length]; for (int i = 0; i < oldResultPoints.length; i++) { ResultPoint oldPoint = oldResultPoints[i]; if (oldPoint != null) { newResultPoints[i] = new ResultPoint(oldPoint.getX() + xOffset, oldPoint.getY() + yOffset); } } Result newResult = new Result(result.getText(), result.getRawBytes(), result.getNumBits(), newResultPoints, result.getBarcodeFormat(), result.getTimestamp()); newResult.putAllMetadata(result.getResultMetadata()); return newResult; } }
if (currentDepth > MAX_DEPTH) { return; } Result result; try { result = delegate.decode(image, hints); } catch (ReaderException ignored) { return; } boolean alreadyFound = false; for (Result existingResult : results) { if (existingResult.getText().equals(result.getText())) { alreadyFound = true; break; } } if (!alreadyFound) { results.add(translateResultPoints(result, xOffset, yOffset)); } ResultPoint[] resultPoints = result.getResultPoints(); if (resultPoints == null || resultPoints.length == 0) { return; } int width = image.getWidth(); int height = image.getHeight(); float minX = width; float minY = height; float maxX = 0.0f; float maxY = 0.0f; for (ResultPoint point : resultPoints) { if (point == null) { continue; } float x = point.getX(); float y = point.getY(); if (x < minX) { minX = x; } if (y < minY) { minY = y; } if (x > maxX) { maxX = x; } if (y > maxY) { maxY = y; } } // Decode left of barcode if (minX > MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, 0, (int) minX, height), hints, results, xOffset, yOffset, currentDepth + 1); } // Decode above barcode if (minY > MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, 0, width, (int) minY), hints, results, xOffset, yOffset, currentDepth + 1); } // Decode right of barcode if (maxX < width - MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop((int) maxX, 0, width - (int) maxX, height), hints, results, xOffset + (int) maxX, yOffset, currentDepth + 1); } // Decode below barcode if (maxY < height - MIN_DIMENSION_TO_RECUR) { doDecodeMultiple(image.crop(0, (int) maxY, width, height - (int) maxY), hints, results, xOffset, yOffset + (int) maxY, currentDepth + 1); }
579
717
1,296
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/multi/qrcode/QRCodeMultiReader.java
QRCodeMultiReader
processStructuredAppend
class QRCodeMultiReader extends QRCodeReader implements MultipleBarcodeReader { private static final Result[] EMPTY_RESULT_ARRAY = new Result[0]; private static final ResultPoint[] NO_POINTS = new ResultPoint[0]; @Override public Result[] decodeMultiple(BinaryBitmap image) throws NotFoundException { return decodeMultiple(image, null); } @Override public Result[] decodeMultiple(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException { List<Result> results = new ArrayList<>(); DetectorResult[] detectorResults = new MultiDetector(image.getBlackMatrix()).detectMulti(hints); for (DetectorResult detectorResult : detectorResults) { try { DecoderResult decoderResult = getDecoder().decode(detectorResult.getBits(), hints); ResultPoint[] points = detectorResult.getPoints(); // If the code was mirrored: swap the bottom-left and the top-right points. if (decoderResult.getOther() instanceof QRCodeDecoderMetaData) { ((QRCodeDecoderMetaData) decoderResult.getOther()).applyMirroredCorrection(points); } Result result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), points, BarcodeFormat.QR_CODE); List<byte[]> byteSegments = decoderResult.getByteSegments(); if (byteSegments != null) { result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments); } String ecLevel = decoderResult.getECLevel(); if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } if (decoderResult.hasStructuredAppend()) { result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE, decoderResult.getStructuredAppendSequenceNumber()); result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY, decoderResult.getStructuredAppendParity()); } results.add(result); } catch (ReaderException re) { // ignore and continue } } if (results.isEmpty()) { return EMPTY_RESULT_ARRAY; } else { results = processStructuredAppend(results); return results.toArray(EMPTY_RESULT_ARRAY); } } static List<Result> processStructuredAppend(List<Result> results) {<FILL_FUNCTION_BODY>} private static final class SAComparator implements Comparator<Result>, Serializable { @Override public int compare(Result a, Result b) { int aNumber = (int) a.getResultMetadata().get(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE); int bNumber = (int) b.getResultMetadata().get(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE); return Integer.compare(aNumber, bNumber); } } }
List<Result> newResults = new ArrayList<>(); List<Result> saResults = new ArrayList<>(); for (Result result : results) { if (result.getResultMetadata().containsKey(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE)) { saResults.add(result); } else { newResults.add(result); } } if (saResults.isEmpty()) { return results; } // sort and concatenate the SA list items Collections.sort(saResults, new SAComparator()); StringBuilder newText = new StringBuilder(); ByteArrayOutputStream newRawBytes = new ByteArrayOutputStream(); ByteArrayOutputStream newByteSegment = new ByteArrayOutputStream(); for (Result saResult : saResults) { newText.append(saResult.getText()); byte[] saBytes = saResult.getRawBytes(); newRawBytes.write(saBytes, 0, saBytes.length); @SuppressWarnings("unchecked") Iterable<byte[]> byteSegments = (Iterable<byte[]>) saResult.getResultMetadata().get(ResultMetadataType.BYTE_SEGMENTS); if (byteSegments != null) { for (byte[] segment : byteSegments) { newByteSegment.write(segment, 0, segment.length); } } } Result newResult = new Result(newText.toString(), newRawBytes.toByteArray(), NO_POINTS, BarcodeFormat.QR_CODE); if (newByteSegment.size() > 0) { newResult.putMetadata(ResultMetadataType.BYTE_SEGMENTS, Collections.singletonList(newByteSegment.toByteArray())); } newResults.add(newResult); return newResults;
796
455
1,251
<methods>public non-sealed void <init>() ,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public final com.google.zxing.Result decode(com.google.zxing.BinaryBitmap, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public void reset() <variables>private static final com.google.zxing.ResultPoint[] NO_POINTS,private final com.google.zxing.qrcode.decoder.Decoder decoder
zxing_zxing
zxing/core/src/main/java/com/google/zxing/multi/qrcode/detector/MultiDetector.java
MultiDetector
detectMulti
class MultiDetector extends Detector { private static final DetectorResult[] EMPTY_DETECTOR_RESULTS = new DetectorResult[0]; public MultiDetector(BitMatrix image) { super(image); } public DetectorResult[] detectMulti(Map<DecodeHintType,?> hints) throws NotFoundException {<FILL_FUNCTION_BODY>} }
BitMatrix image = getImage(); ResultPointCallback resultPointCallback = hints == null ? null : (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK); MultiFinderPatternFinder finder = new MultiFinderPatternFinder(image, resultPointCallback); FinderPatternInfo[] infos = finder.findMulti(hints); if (infos.length == 0) { throw NotFoundException.getNotFoundInstance(); } List<DetectorResult> result = new ArrayList<>(); for (FinderPatternInfo info : infos) { try { result.add(processFinderPatternInfo(info)); } catch (ReaderException e) { // ignore } } if (result.isEmpty()) { return EMPTY_DETECTOR_RESULTS; } else { return result.toArray(EMPTY_DETECTOR_RESULTS); }
104
246
350
<methods>public void <init>(com.google.zxing.common.BitMatrix) ,public com.google.zxing.common.DetectorResult detect() throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public final com.google.zxing.common.DetectorResult detect(Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException<variables>private final non-sealed com.google.zxing.common.BitMatrix image,private com.google.zxing.ResultPointCallback resultPointCallback
zxing_zxing
zxing/core/src/main/java/com/google/zxing/multi/qrcode/detector/MultiFinderPatternFinder.java
ModuleSizeComparator
selectMultipleBestPatterns
class ModuleSizeComparator implements Comparator<FinderPattern>, Serializable { @Override public int compare(FinderPattern center1, FinderPattern center2) { float value = center2.getEstimatedModuleSize() - center1.getEstimatedModuleSize(); return value < 0.0 ? -1 : value > 0.0 ? 1 : 0; } } public MultiFinderPatternFinder(BitMatrix image, ResultPointCallback resultPointCallback) { super(image, resultPointCallback); } /** * @return the 3 best {@link FinderPattern}s from our list of candidates. The "best" are * those that have been detected at least 2 times, and whose module * size differs from the average among those patterns the least * @throws NotFoundException if 3 such finder patterns do not exist */ private FinderPattern[][] selectMultipleBestPatterns() throws NotFoundException {<FILL_FUNCTION_BODY>
List<FinderPattern> possibleCenters = new ArrayList<>(); for (FinderPattern fp : getPossibleCenters()) { if (fp.getCount() >= 2) { possibleCenters.add(fp); } } int size = possibleCenters.size(); if (size < 3) { // Couldn't find enough finder patterns throw NotFoundException.getNotFoundInstance(); } /* * Begin HE modifications to safely detect multiple codes of equal size */ if (size == 3) { return new FinderPattern[][] { possibleCenters.toArray(EMPTY_FP_ARRAY) }; } // Sort by estimated module size to speed up the upcoming checks Collections.sort(possibleCenters, new ModuleSizeComparator()); /* * Now lets start: build a list of tuples of three finder locations that * - feature similar module sizes * - are placed in a distance so the estimated module count is within the QR specification * - have similar distance between upper left/right and left top/bottom finder patterns * - form a triangle with 90° angle (checked by comparing top right/bottom left distance * with pythagoras) * * Note: we allow each point to be used for more than one code region: this might seem * counterintuitive at first, but the performance penalty is not that big. At this point, * we cannot make a good quality decision whether the three finders actually represent * a QR code, or are just by chance laid out so it looks like there might be a QR code there. * So, if the layout seems right, lets have the decoder try to decode. */ List<FinderPattern[]> results = new ArrayList<>(); // holder for the results for (int i1 = 0; i1 < (size - 2); i1++) { FinderPattern p1 = possibleCenters.get(i1); if (p1 == null) { continue; } for (int i2 = i1 + 1; i2 < (size - 1); i2++) { FinderPattern p2 = possibleCenters.get(i2); if (p2 == null) { continue; } // Compare the expected module sizes; if they are really off, skip float vModSize12 = (p1.getEstimatedModuleSize() - p2.getEstimatedModuleSize()) / Math.min(p1.getEstimatedModuleSize(), p2.getEstimatedModuleSize()); float vModSize12A = Math.abs(p1.getEstimatedModuleSize() - p2.getEstimatedModuleSize()); if (vModSize12A > DIFF_MODSIZE_CUTOFF && vModSize12 >= DIFF_MODSIZE_CUTOFF_PERCENT) { // break, since elements are ordered by the module size deviation there cannot be // any more interesting elements for the given p1. break; } for (int i3 = i2 + 1; i3 < size; i3++) { FinderPattern p3 = possibleCenters.get(i3); if (p3 == null) { continue; } // Compare the expected module sizes; if they are really off, skip float vModSize23 = (p2.getEstimatedModuleSize() - p3.getEstimatedModuleSize()) / Math.min(p2.getEstimatedModuleSize(), p3.getEstimatedModuleSize()); float vModSize23A = Math.abs(p2.getEstimatedModuleSize() - p3.getEstimatedModuleSize()); if (vModSize23A > DIFF_MODSIZE_CUTOFF && vModSize23 >= DIFF_MODSIZE_CUTOFF_PERCENT) { // break, since elements are ordered by the module size deviation there cannot be // any more interesting elements for the given p1. break; } FinderPattern[] test = {p1, p2, p3}; ResultPoint.orderBestPatterns(test); // Calculate the distances: a = topleft-bottomleft, b=topleft-topright, c = diagonal FinderPatternInfo info = new FinderPatternInfo(test); float dA = ResultPoint.distance(info.getTopLeft(), info.getBottomLeft()); float dC = ResultPoint.distance(info.getTopRight(), info.getBottomLeft()); float dB = ResultPoint.distance(info.getTopLeft(), info.getTopRight()); // Check the sizes float estimatedModuleCount = (dA + dB) / (p1.getEstimatedModuleSize() * 2.0f); if (estimatedModuleCount > MAX_MODULE_COUNT_PER_EDGE || estimatedModuleCount < MIN_MODULE_COUNT_PER_EDGE) { continue; } // Calculate the difference of the edge lengths in percent float vABBC = Math.abs((dA - dB) / Math.min(dA, dB)); if (vABBC >= 0.1f) { continue; } // Calculate the diagonal length by assuming a 90° angle at topleft float dCpy = (float) Math.sqrt((double) dA * dA + (double) dB * dB); // Compare to the real distance in % float vPyC = Math.abs((dC - dCpy) / Math.min(dC, dCpy)); if (vPyC >= 0.1f) { continue; } // All tests passed! results.add(test); } } } if (!results.isEmpty()) { return results.toArray(EMPTY_FP_2D_ARRAY); } // Nothing found! throw NotFoundException.getNotFoundInstance();
245
1,468
1,713
<methods>public void <init>(com.google.zxing.common.BitMatrix) ,public void <init>(com.google.zxing.common.BitMatrix, com.google.zxing.ResultPointCallback) <variables>private static final int CENTER_QUORUM,protected static final int MAX_MODULES,protected static final int MIN_SKIP,private final non-sealed int[] crossCheckStateCount,private boolean hasSkipped,private final non-sealed com.google.zxing.common.BitMatrix image,private static final com.google.zxing.qrcode.detector.FinderPatternFinder.EstimatedModuleComparator moduleComparator,private final non-sealed List<com.google.zxing.qrcode.detector.FinderPattern> possibleCenters,private final non-sealed com.google.zxing.ResultPointCallback resultPointCallback
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/CodaBarWriter.java
CodaBarWriter
encode
class CodaBarWriter extends OneDimensionalCodeWriter { private static final char[] START_END_CHARS = {'A', 'B', 'C', 'D'}; private static final char[] ALT_START_END_CHARS = {'T', 'N', '*', 'E'}; private static final char[] CHARS_WHICH_ARE_TEN_LENGTH_EACH_AFTER_DECODED = {'/', ':', '+', '.'}; private static final char DEFAULT_GUARD = START_END_CHARS[0]; @Override protected Collection<BarcodeFormat> getSupportedWriteFormats() { return Collections.singleton(BarcodeFormat.CODABAR); } @Override public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>} }
if (contents.length() < 2) { // Can't have a start/end guard, so tentatively add default guards contents = DEFAULT_GUARD + contents + DEFAULT_GUARD; } else { // Verify input and calculate decoded length. char firstChar = Character.toUpperCase(contents.charAt(0)); char lastChar = Character.toUpperCase(contents.charAt(contents.length() - 1)); boolean startsNormal = CodaBarReader.arrayContains(START_END_CHARS, firstChar); boolean endsNormal = CodaBarReader.arrayContains(START_END_CHARS, lastChar); boolean startsAlt = CodaBarReader.arrayContains(ALT_START_END_CHARS, firstChar); boolean endsAlt = CodaBarReader.arrayContains(ALT_START_END_CHARS, lastChar); if (startsNormal) { if (!endsNormal) { throw new IllegalArgumentException("Invalid start/end guards: " + contents); } // else already has valid start/end } else if (startsAlt) { if (!endsAlt) { throw new IllegalArgumentException("Invalid start/end guards: " + contents); } // else already has valid start/end } else { // Doesn't start with a guard if (endsNormal || endsAlt) { throw new IllegalArgumentException("Invalid start/end guards: " + contents); } // else doesn't end with guard either, so add a default contents = DEFAULT_GUARD + contents + DEFAULT_GUARD; } } // The start character and the end character are decoded to 10 length each. int resultLength = 20; for (int i = 1; i < contents.length() - 1; i++) { if (Character.isDigit(contents.charAt(i)) || contents.charAt(i) == '-' || contents.charAt(i) == '$') { resultLength += 9; } else if (CodaBarReader.arrayContains(CHARS_WHICH_ARE_TEN_LENGTH_EACH_AFTER_DECODED, contents.charAt(i))) { resultLength += 10; } else { throw new IllegalArgumentException("Cannot encode : '" + contents.charAt(i) + '\''); } } // A blank is placed between each character. resultLength += contents.length() - 1; boolean[] result = new boolean[resultLength]; int position = 0; for (int index = 0; index < contents.length(); index++) { char c = Character.toUpperCase(contents.charAt(index)); if (index == 0 || index == contents.length() - 1) { // The start/end chars are not in the CodaBarReader.ALPHABET. switch (c) { case 'T': c = 'A'; break; case 'N': c = 'B'; break; case '*': c = 'C'; break; case 'E': c = 'D'; break; } } int code = 0; for (int i = 0; i < CodaBarReader.ALPHABET.length; i++) { // Found any, because I checked above. if (c == CodaBarReader.ALPHABET[i]) { code = CodaBarReader.CHARACTER_ENCODINGS[i]; break; } } boolean color = true; int counter = 0; int bit = 0; while (bit < 7) { // A character consists of 7 digit. result[position] = color; position++; if (((code >> (6 - bit)) & 1) == 0 || counter == 1) { color = !color; // Flip the color. bit++; counter = 0; } else { counter++; } } if (index < contents.length() - 1) { result[position] = false; position++; } } return result;
210
1,047
1,257
<methods>public non-sealed void <init>() ,public abstract boolean[] encode(java.lang.String) ,public boolean[] encode(java.lang.String, Map<com.google.zxing.EncodeHintType,?>) ,public final com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int) ,public com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int, Map<com.google.zxing.EncodeHintType,?>) ,public int getDefaultMargin() <variables>private static final java.util.regex.Pattern NUMERIC
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/Code39Writer.java
Code39Writer
encode
class Code39Writer extends OneDimensionalCodeWriter { @Override protected Collection<BarcodeFormat> getSupportedWriteFormats() { return Collections.singleton(BarcodeFormat.CODE_39); } @Override public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>} private static void toIntArray(int a, int[] toReturn) { for (int i = 0; i < 9; i++) { int temp = a & (1 << (8 - i)); toReturn[i] = temp == 0 ? 1 : 2; } } private static String tryToConvertToExtendedMode(String contents) { int length = contents.length(); StringBuilder extendedContent = new StringBuilder(); for (int i = 0; i < length; i++) { char character = contents.charAt(i); switch (character) { case '\u0000': extendedContent.append("%U"); break; case ' ': case '-': case '.': extendedContent.append(character); break; case '@': extendedContent.append("%V"); break; case '`': extendedContent.append("%W"); break; default: if (character <= 26) { extendedContent.append('$'); extendedContent.append((char) ('A' + (character - 1))); } else if (character < ' ') { extendedContent.append('%'); extendedContent.append((char) ('A' + (character - 27))); } else if (character <= ',' || character == '/' || character == ':') { extendedContent.append('/'); extendedContent.append((char) ('A' + (character - 33))); } else if (character <= '9') { extendedContent.append((char) ('0' + (character - 48))); } else if (character <= '?') { extendedContent.append('%'); extendedContent.append((char) ('F' + (character - 59))); } else if (character <= 'Z') { extendedContent.append((char) ('A' + (character - 65))); } else if (character <= '_') { extendedContent.append('%'); extendedContent.append((char) ('K' + (character - 91))); } else if (character <= 'z') { extendedContent.append('+'); extendedContent.append((char) ('A' + (character - 97))); } else if (character <= 127) { extendedContent.append('%'); extendedContent.append((char) ('P' + (character - 123))); } else { throw new IllegalArgumentException( "Requested content contains a non-encodable character: '" + contents.charAt(i) + "'"); } break; } } return extendedContent.toString(); } }
int length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length); } for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); if (indexInString < 0) { contents = tryToConvertToExtendedMode(contents); length = contents.length(); if (length > 80) { throw new IllegalArgumentException("Requested contents should be less than 80 digits long, but got " + length + " (extended full ASCII mode)"); } break; } } int[] widths = new int[9]; int codeWidth = 24 + 1 + (13 * length); boolean[] result = new boolean[codeWidth]; toIntArray(Code39Reader.ASTERISK_ENCODING, widths); int pos = appendPattern(result, 0, widths, true); int[] narrowWhite = {1}; pos += appendPattern(result, pos, narrowWhite, false); //append next character to byte matrix for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); pos += appendPattern(result, pos, widths, true); pos += appendPattern(result, pos, narrowWhite, false); } toIntArray(Code39Reader.ASTERISK_ENCODING, widths); appendPattern(result, pos, widths, true); return result;
752
465
1,217
<methods>public non-sealed void <init>() ,public abstract boolean[] encode(java.lang.String) ,public boolean[] encode(java.lang.String, Map<com.google.zxing.EncodeHintType,?>) ,public final com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int) ,public com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int, Map<com.google.zxing.EncodeHintType,?>) ,public int getDefaultMargin() <variables>private static final java.util.regex.Pattern NUMERIC
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/Code93Writer.java
Code93Writer
encode
class Code93Writer extends OneDimensionalCodeWriter { @Override protected Collection<BarcodeFormat> getSupportedWriteFormats() { return Collections.singleton(BarcodeFormat.CODE_93); } /** * @param contents barcode contents to encode. It should not be encoded for extended characters. * @return a {@code boolean[]} of horizontal pixels (false = white, true = black) */ @Override public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>} /** * @param target output to append to * @param pos start position * @param pattern pattern to append * @param startColor unused * @return 9 * @deprecated without replacement; intended as an internal-only method */ @Deprecated protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { for (int bit : pattern) { target[pos++] = bit != 0; } return 9; } private static int appendPattern(boolean[] target, int pos, int a) { for (int i = 0; i < 9; i++) { int temp = a & (1 << (8 - i)); target[pos + i] = temp != 0; } return 9; } private static int computeChecksumIndex(String contents, int maxWeight) { int weight = 1; int total = 0; for (int i = contents.length() - 1; i >= 0; i--) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); total += indexInString * weight; if (++weight > maxWeight) { weight = 1; } } return total % 47; } static String convertToExtended(String contents) { int length = contents.length(); StringBuilder extendedContent = new StringBuilder(length * 2); for (int i = 0; i < length; i++) { char character = contents.charAt(i); // ($)=a, (%)=b, (/)=c, (+)=d. see Code93Reader.ALPHABET_STRING if (character == 0) { // NUL: (%)U extendedContent.append("bU"); } else if (character <= 26) { // SOH - SUB: ($)A - ($)Z extendedContent.append('a'); extendedContent.append((char) ('A' + character - 1)); } else if (character <= 31) { // ESC - US: (%)A - (%)E extendedContent.append('b'); extendedContent.append((char) ('A' + character - 27)); } else if (character == ' ' || character == '$' || character == '%' || character == '+') { // space $ % + extendedContent.append(character); } else if (character <= ',') { // ! " # & ' ( ) * ,: (/)A - (/)L extendedContent.append('c'); extendedContent.append((char) ('A' + character - '!')); } else if (character <= '9') { extendedContent.append(character); } else if (character == ':') { // :: (/)Z extendedContent.append("cZ"); } else if (character <= '?') { // ; - ?: (%)F - (%)J extendedContent.append('b'); extendedContent.append((char) ('F' + character - ';')); } else if (character == '@') { // @: (%)V extendedContent.append("bV"); } else if (character <= 'Z') { // A - Z extendedContent.append(character); } else if (character <= '_') { // [ - _: (%)K - (%)O extendedContent.append('b'); extendedContent.append((char) ('K' + character - '[')); } else if (character == '`') { // `: (%)W extendedContent.append("bW"); } else if (character <= 'z') { // a - z: (*)A - (*)Z extendedContent.append('d'); extendedContent.append((char) ('A' + character - 'a')); } else if (character <= 127) { // { - DEL: (%)P - (%)T extendedContent.append('b'); extendedContent.append((char) ('P' + character - '{')); } else { throw new IllegalArgumentException( "Requested content contains a non-encodable character: '" + character + "'"); } } return extendedContent.toString(); } }
contents = convertToExtended(contents); int length = contents.length(); if (length > 80) { throw new IllegalArgumentException("Requested contents should be less than 80 digits long after " + "converting to extended encoding, but got " + length); } //length of code + 2 start/stop characters + 2 checksums, each of 9 bits, plus a termination bar int codeWidth = (contents.length() + 2 + 2) * 9 + 1; boolean[] result = new boolean[codeWidth]; //start character (*) int pos = appendPattern(result, 0, Code93Reader.ASTERISK_ENCODING); for (int i = 0; i < length; i++) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[indexInString]); } //add two checksums int check1 = computeChecksumIndex(contents, 20); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check1]); //append the contents to reflect the first checksum added contents += Code93Reader.ALPHABET_STRING.charAt(check1); int check2 = computeChecksumIndex(contents, 15); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check2]); //end character (*) pos += appendPattern(result, pos, Code93Reader.ASTERISK_ENCODING); //termination bar (single black bar) result[pos] = true; return result;
1,223
449
1,672
<methods>public non-sealed void <init>() ,public abstract boolean[] encode(java.lang.String) ,public boolean[] encode(java.lang.String, Map<com.google.zxing.EncodeHintType,?>) ,public final com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int) ,public com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int, Map<com.google.zxing.EncodeHintType,?>) ,public int getDefaultMargin() <variables>private static final java.util.regex.Pattern NUMERIC
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/EAN13Reader.java
EAN13Reader
decodeMiddle
class EAN13Reader extends UPCEANReader { // For an EAN-13 barcode, the first digit is represented by the parities used // to encode the next six digits, according to the table below. For example, // if the barcode is 5 123456 789012 then the value of the first digit is // signified by using odd for '1', even for '2', even for '3', odd for '4', // odd for '5', and even for '6'. See http://en.wikipedia.org/wiki/EAN-13 // // Parity of next 6 digits // Digit 0 1 2 3 4 5 // 0 Odd Odd Odd Odd Odd Odd // 1 Odd Odd Even Odd Even Even // 2 Odd Odd Even Even Odd Even // 3 Odd Odd Even Even Even Odd // 4 Odd Even Odd Odd Even Even // 5 Odd Even Even Odd Odd Even // 6 Odd Even Even Even Odd Odd // 7 Odd Even Odd Even Odd Even // 8 Odd Even Odd Even Even Odd // 9 Odd Even Even Odd Even Odd // // Note that the encoding for '0' uses the same parity as a UPC barcode. Hence // a UPC barcode can be converted to an EAN-13 barcode by prepending a 0. // // The encoding is represented by the following array, which is a bit pattern // using Odd = 0 and Even = 1. For example, 5 is represented by: // // Odd Even Even Odd Odd Even // in binary: // 0 1 1 0 0 1 == 0x19 // static final int[] FIRST_DIGIT_ENCODINGS = { 0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A }; private final int[] decodeMiddleCounters; public EAN13Reader() { decodeMiddleCounters = new int[4]; } @Override protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException {<FILL_FUNCTION_BODY>} @Override BarcodeFormat getBarcodeFormat() { return BarcodeFormat.EAN_13; } /** * Based on pattern of odd-even ('L' and 'G') patterns used to encoded the explicitly-encoded * digits in a barcode, determines the implicitly encoded first digit and adds it to the * result string. * * @param resultString string to insert decoded first digit into * @param lgPatternFound int whose bits indicates the pattern of odd/even L/G patterns used to * encode digits * @throws NotFoundException if first digit cannot be determined */ private static void determineFirstDigit(StringBuilder resultString, int lgPatternFound) throws NotFoundException { for (int d = 0; d < 10; d++) { if (lgPatternFound == FIRST_DIGIT_ENCODINGS[d]) { resultString.insert(0, (char) ('0' + d)); return; } } throw NotFoundException.getNotFoundInstance(); } }
int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; int lgPatternFound = 0; for (int x = 0; x < 6 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_AND_G_PATTERNS); resultString.append((char) ('0' + bestMatch % 10)); for (int counter : counters) { rowOffset += counter; } if (bestMatch >= 10) { lgPatternFound |= 1 << (5 - x); } } determineFirstDigit(resultString, lgPatternFound); int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN); rowOffset = middleRange[1]; for (int x = 0; x < 6 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); resultString.append((char) ('0' + bestMatch)); for (int counter : counters) { rowOffset += counter; } } return rowOffset;
978
366
1,344
<methods>public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, int[], Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException<variables>static final int[] END_PATTERN,static final non-sealed int[][] L_AND_G_PATTERNS,static final int[][] L_PATTERNS,private static final float MAX_AVG_VARIANCE,private static final float MAX_INDIVIDUAL_VARIANCE,static final int[] MIDDLE_PATTERN,static final int[] START_END_PATTERN,private final non-sealed java.lang.StringBuilder decodeRowStringBuffer,private final non-sealed com.google.zxing.oned.EANManufacturerOrgSupport eanManSupport,private final non-sealed com.google.zxing.oned.UPCEANExtensionSupport extensionReader
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/EAN13Writer.java
EAN13Writer
encode
class EAN13Writer extends UPCEANWriter { private static final int CODE_WIDTH = 3 + // start guard (7 * 6) + // left bars 5 + // middle guard (7 * 6) + // right bars 3; // end guard @Override protected Collection<BarcodeFormat> getSupportedWriteFormats() { return Collections.singleton(BarcodeFormat.EAN_13); } @Override public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>} }
int length = contents.length(); switch (length) { case 12: // No check digit present, calculate it and add it int check; try { check = UPCEANReader.getStandardUPCEANChecksum(contents); } catch (FormatException fe) { throw new IllegalArgumentException(fe); } contents += check; break; case 13: try { if (!UPCEANReader.checkStandardUPCEANChecksum(contents)) { throw new IllegalArgumentException("Contents do not pass checksum"); } } catch (FormatException ignored) { throw new IllegalArgumentException("Illegal contents"); } break; default: throw new IllegalArgumentException( "Requested contents should be 12 or 13 digits long, but got " + length); } checkNumeric(contents); int firstDigit = Character.digit(contents.charAt(0), 10); int parities = EAN13Reader.FIRST_DIGIT_ENCODINGS[firstDigit]; boolean[] result = new boolean[CODE_WIDTH]; int pos = 0; pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, true); // See EAN13Reader for a description of how the first digit & left bars are encoded for (int i = 1; i <= 6; i++) { int digit = Character.digit(contents.charAt(i), 10); if ((parities >> (6 - i) & 1) == 1) { digit += 10; } pos += appendPattern(result, pos, UPCEANReader.L_AND_G_PATTERNS[digit], false); } pos += appendPattern(result, pos, UPCEANReader.MIDDLE_PATTERN, false); for (int i = 7; i <= 12; i++) { int digit = Character.digit(contents.charAt(i), 10); pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], true); } appendPattern(result, pos, UPCEANReader.START_END_PATTERN, true); return result;
146
580
726
<methods>public non-sealed void <init>() ,public int getDefaultMargin() <variables>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/EAN8Reader.java
EAN8Reader
decodeMiddle
class EAN8Reader extends UPCEANReader { private final int[] decodeMiddleCounters; public EAN8Reader() { decodeMiddleCounters = new int[4]; } @Override protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder result) throws NotFoundException {<FILL_FUNCTION_BODY>} @Override BarcodeFormat getBarcodeFormat() { return BarcodeFormat.EAN_8; } }
int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; for (int x = 0; x < 4 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); result.append((char) ('0' + bestMatch)); for (int counter : counters) { rowOffset += counter; } } int[] middleRange = findGuardPattern(row, rowOffset, true, MIDDLE_PATTERN); rowOffset = middleRange[1]; for (int x = 0; x < 4 && rowOffset < end; x++) { int bestMatch = decodeDigit(row, counters, rowOffset, L_PATTERNS); result.append((char) ('0' + bestMatch)); for (int counter : counters) { rowOffset += counter; } } return rowOffset;
138
300
438
<methods>public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, int[], Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException<variables>static final int[] END_PATTERN,static final non-sealed int[][] L_AND_G_PATTERNS,static final int[][] L_PATTERNS,private static final float MAX_AVG_VARIANCE,private static final float MAX_INDIVIDUAL_VARIANCE,static final int[] MIDDLE_PATTERN,static final int[] START_END_PATTERN,private final non-sealed java.lang.StringBuilder decodeRowStringBuffer,private final non-sealed com.google.zxing.oned.EANManufacturerOrgSupport eanManSupport,private final non-sealed com.google.zxing.oned.UPCEANExtensionSupport extensionReader
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/EAN8Writer.java
EAN8Writer
encode
class EAN8Writer extends UPCEANWriter { private static final int CODE_WIDTH = 3 + // start guard (7 * 4) + // left bars 5 + // middle guard (7 * 4) + // right bars 3; // end guard @Override protected Collection<BarcodeFormat> getSupportedWriteFormats() { return Collections.singleton(BarcodeFormat.EAN_8); } /** * @return a byte array of horizontal pixels (false = white, true = black) */ @Override public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>} }
int length = contents.length(); switch (length) { case 7: // No check digit present, calculate it and add it int check; try { check = UPCEANReader.getStandardUPCEANChecksum(contents); } catch (FormatException fe) { throw new IllegalArgumentException(fe); } contents += check; break; case 8: try { if (!UPCEANReader.checkStandardUPCEANChecksum(contents)) { throw new IllegalArgumentException("Contents do not pass checksum"); } } catch (FormatException ignored) { throw new IllegalArgumentException("Illegal contents"); } break; default: throw new IllegalArgumentException( "Requested contents should be 7 or 8 digits long, but got " + length); } checkNumeric(contents); boolean[] result = new boolean[CODE_WIDTH]; int pos = 0; pos += appendPattern(result, pos, UPCEANReader.START_END_PATTERN, true); for (int i = 0; i <= 3; i++) { int digit = Character.digit(contents.charAt(i), 10); pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], false); } pos += appendPattern(result, pos, UPCEANReader.MIDDLE_PATTERN, false); for (int i = 4; i <= 7; i++) { int digit = Character.digit(contents.charAt(i), 10); pos += appendPattern(result, pos, UPCEANReader.L_PATTERNS[digit], true); } appendPattern(result, pos, UPCEANReader.START_END_PATTERN, true); return result;
170
468
638
<methods>public non-sealed void <init>() ,public int getDefaultMargin() <variables>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/ITFWriter.java
ITFWriter
encode
class ITFWriter extends OneDimensionalCodeWriter { private static final int[] START_PATTERN = {1, 1, 1, 1}; private static final int[] END_PATTERN = {3, 1, 1}; private static final int W = 3; // Pixel width of a 3x wide line private static final int N = 1; // Pixed width of a narrow line // See ITFReader.PATTERNS private static final int[][] PATTERNS = { {N, N, W, W, N}, // 0 {W, N, N, N, W}, // 1 {N, W, N, N, W}, // 2 {W, W, N, N, N}, // 3 {N, N, W, N, W}, // 4 {W, N, W, N, N}, // 5 {N, W, W, N, N}, // 6 {N, N, N, W, W}, // 7 {W, N, N, W, N}, // 8 {N, W, N, W, N} // 9 }; @Override protected Collection<BarcodeFormat> getSupportedWriteFormats() { return Collections.singleton(BarcodeFormat.ITF); } @Override public boolean[] encode(String contents) {<FILL_FUNCTION_BODY>} }
int length = contents.length(); if (length % 2 != 0) { throw new IllegalArgumentException("The length of the input should be even"); } if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length); } checkNumeric(contents); boolean[] result = new boolean[9 + 9 * length]; int pos = appendPattern(result, 0, START_PATTERN, true); for (int i = 0; i < length; i += 2) { int one = Character.digit(contents.charAt(i), 10); int two = Character.digit(contents.charAt(i + 1), 10); int[] encoding = new int[10]; for (int j = 0; j < 5; j++) { encoding[2 * j] = PATTERNS[one][j]; encoding[2 * j + 1] = PATTERNS[two][j]; } pos += appendPattern(result, pos, encoding, true); } appendPattern(result, pos, END_PATTERN, true); return result;
366
306
672
<methods>public non-sealed void <init>() ,public abstract boolean[] encode(java.lang.String) ,public boolean[] encode(java.lang.String, Map<com.google.zxing.EncodeHintType,?>) ,public final com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int) ,public com.google.zxing.common.BitMatrix encode(java.lang.String, com.google.zxing.BarcodeFormat, int, int, Map<com.google.zxing.EncodeHintType,?>) ,public int getDefaultMargin() <variables>private static final java.util.regex.Pattern NUMERIC
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/MultiFormatOneDReader.java
MultiFormatOneDReader
decodeRow
class MultiFormatOneDReader extends OneDReader { private static final OneDReader[] EMPTY_ONED_ARRAY = new OneDReader[0]; private final OneDReader[] readers; public MultiFormatOneDReader(Map<DecodeHintType,?> hints) { @SuppressWarnings("unchecked") Collection<BarcodeFormat> possibleFormats = hints == null ? null : (Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS); boolean useCode39CheckDigit = hints != null && hints.get(DecodeHintType.ASSUME_CODE_39_CHECK_DIGIT) != null; Collection<OneDReader> readers = new ArrayList<>(); if (possibleFormats != null) { if (possibleFormats.contains(BarcodeFormat.EAN_13) || possibleFormats.contains(BarcodeFormat.UPC_A) || possibleFormats.contains(BarcodeFormat.EAN_8) || possibleFormats.contains(BarcodeFormat.UPC_E)) { readers.add(new MultiFormatUPCEANReader(hints)); } if (possibleFormats.contains(BarcodeFormat.CODE_39)) { readers.add(new Code39Reader(useCode39CheckDigit)); } if (possibleFormats.contains(BarcodeFormat.CODE_93)) { readers.add(new Code93Reader()); } if (possibleFormats.contains(BarcodeFormat.CODE_128)) { readers.add(new Code128Reader()); } if (possibleFormats.contains(BarcodeFormat.ITF)) { readers.add(new ITFReader()); } if (possibleFormats.contains(BarcodeFormat.CODABAR)) { readers.add(new CodaBarReader()); } if (possibleFormats.contains(BarcodeFormat.RSS_14)) { readers.add(new RSS14Reader()); } if (possibleFormats.contains(BarcodeFormat.RSS_EXPANDED)) { readers.add(new RSSExpandedReader()); } } if (readers.isEmpty()) { readers.add(new MultiFormatUPCEANReader(hints)); readers.add(new Code39Reader()); readers.add(new CodaBarReader()); readers.add(new Code93Reader()); readers.add(new Code128Reader()); readers.add(new ITFReader()); readers.add(new RSS14Reader()); readers.add(new RSSExpandedReader()); } this.readers = readers.toArray(EMPTY_ONED_ARRAY); } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException {<FILL_FUNCTION_BODY>} @Override public void reset() { for (Reader reader : readers) { reader.reset(); } } }
for (OneDReader reader : readers) { try { return reader.decodeRow(rowNumber, row, hints); } catch (ReaderException re) { // continue } } throw NotFoundException.getNotFoundInstance();
805
66
871
<methods>public non-sealed void <init>() ,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public abstract com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public void reset() <variables>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/MultiFormatUPCEANReader.java
MultiFormatUPCEANReader
decodeRow
class MultiFormatUPCEANReader extends OneDReader { private static final UPCEANReader[] EMPTY_READER_ARRAY = new UPCEANReader[0]; private final UPCEANReader[] readers; public MultiFormatUPCEANReader(Map<DecodeHintType,?> hints) { @SuppressWarnings("unchecked") Collection<BarcodeFormat> possibleFormats = hints == null ? null : (Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS); Collection<UPCEANReader> readers = new ArrayList<>(); if (possibleFormats != null) { if (possibleFormats.contains(BarcodeFormat.EAN_13)) { readers.add(new EAN13Reader()); } else if (possibleFormats.contains(BarcodeFormat.UPC_A)) { readers.add(new UPCAReader()); } if (possibleFormats.contains(BarcodeFormat.EAN_8)) { readers.add(new EAN8Reader()); } if (possibleFormats.contains(BarcodeFormat.UPC_E)) { readers.add(new UPCEReader()); } } if (readers.isEmpty()) { readers.add(new EAN13Reader()); // UPC-A is covered by EAN-13 readers.add(new EAN8Reader()); readers.add(new UPCEReader()); } this.readers = readers.toArray(EMPTY_READER_ARRAY); } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException {<FILL_FUNCTION_BODY>} @Override public void reset() { for (Reader reader : readers) { reader.reset(); } } }
// Compute this location once and reuse it on multiple implementations int[] startGuardPattern = UPCEANReader.findStartGuardPattern(row); for (UPCEANReader reader : readers) { try { Result result = reader.decodeRow(rowNumber, row, startGuardPattern, hints); // Special case: a 12-digit code encoded in UPC-A is identical to a "0" // followed by those 12 digits encoded as EAN-13. Each will recognize such a code, // UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with "0". // Individually these are correct and their readers will both read such a code // and correctly call it EAN-13, or UPC-A, respectively. // // In this case, if we've been looking for both types, we'd like to call it // a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A // result if appropriate. // // But, don't return UPC-A if UPC-A was not a requested format! boolean ean13MayBeUPCA = result.getBarcodeFormat() == BarcodeFormat.EAN_13 && result.getText().charAt(0) == '0'; @SuppressWarnings("unchecked") Collection<BarcodeFormat> possibleFormats = hints == null ? null : (Collection<BarcodeFormat>) hints.get(DecodeHintType.POSSIBLE_FORMATS); boolean canReturnUPCA = possibleFormats == null || possibleFormats.contains(BarcodeFormat.UPC_A); if (ean13MayBeUPCA && canReturnUPCA) { // Transfer the metadata across Result resultUPCA = new Result(result.getText().substring(1), result.getRawBytes(), result.getResultPoints(), BarcodeFormat.UPC_A); resultUPCA.putAllMetadata(result.getResultMetadata()); return resultUPCA; } return result; } catch (ReaderException ignored) { // continue } } throw NotFoundException.getNotFoundInstance();
497
603
1,100
<methods>public non-sealed void <init>() ,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public com.google.zxing.Result decode(com.google.zxing.BinaryBitmap, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.FormatException,public abstract com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public void reset() <variables>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/OneDimensionalCodeWriter.java
OneDimensionalCodeWriter
getDefaultMargin
class OneDimensionalCodeWriter implements Writer { private static final Pattern NUMERIC = Pattern.compile("[0-9]+"); /** * Encode the contents to boolean array expression of one-dimensional barcode. * Start code and end code should be included in result, and side margins should not be included. * * @param contents barcode contents to encode * @return a {@code boolean[]} of horizontal pixels (false = white, true = black) */ public abstract boolean[] encode(String contents); /** * Can be overwritten if the encode requires to read the hints map. Otherwise it defaults to {@code encode}. * @param contents barcode contents to encode * @param hints encoding hints * @return a {@code boolean[]} of horizontal pixels (false = white, true = black) */ public boolean[] encode(String contents, Map<EncodeHintType,?> hints) { return encode(contents); } @Override public final BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { return encode(contents, format, width, height, null); } /** * Encode the contents following specified format. * {@code width} and {@code height} are required size. This method may return bigger size * {@code BitMatrix} when specified size is too small. The user can set both {@code width} and * {@code height} to zero to get minimum size barcode. If negative value is set to {@code width} * or {@code height}, {@code IllegalArgumentException} is thrown. */ @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) { if (contents.isEmpty()) { throw new IllegalArgumentException("Found empty contents"); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Negative size is not allowed. Input: " + width + 'x' + height); } Collection<BarcodeFormat> supportedFormats = getSupportedWriteFormats(); if (supportedFormats != null && !supportedFormats.contains(format)) { throw new IllegalArgumentException("Can only encode " + supportedFormats + ", but got " + format); } int sidesMargin = getDefaultMargin(); if (hints != null && hints.containsKey(EncodeHintType.MARGIN)) { sidesMargin = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString()); } boolean[] code = encode(contents, hints); return renderResult(code, width, height, sidesMargin); } protected Collection<BarcodeFormat> getSupportedWriteFormats() { return null; } /** * @return a byte array of horizontal pixels (0 = white, 1 = black) */ private static BitMatrix renderResult(boolean[] code, int width, int height, int sidesMargin) { int inputWidth = code.length; // Add quiet zone on both sides. int fullWidth = inputWidth + sidesMargin; int outputWidth = Math.max(width, fullWidth); int outputHeight = Math.max(1, height); int multiple = outputWidth / fullWidth; int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; BitMatrix output = new BitMatrix(outputWidth, outputHeight); for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) { if (code[inputX]) { output.setRegion(outputX, 0, multiple, outputHeight); } } return output; } /** * @param contents string to check for numeric characters * @throws IllegalArgumentException if input contains characters other than digits 0-9. */ protected static void checkNumeric(String contents) { if (!NUMERIC.matcher(contents).matches()) { throw new IllegalArgumentException("Input should only contain digits 0-9"); } } /** * @param target encode black/white pattern into this array * @param pos position to start encoding at in {@code target} * @param pattern lengths of black/white runs to encode * @param startColor starting color - false for white, true for black * @return the number of elements added to target. */ protected static int appendPattern(boolean[] target, int pos, int[] pattern, boolean startColor) { boolean color = startColor; int numAdded = 0; for (int len : pattern) { for (int j = 0; j < len; j++) { target[pos++] = color; } numAdded += len; color = !color; // flip color after each segment } return numAdded; } public int getDefaultMargin() {<FILL_FUNCTION_BODY>} }
// CodaBar spec requires a side margin to be more than ten times wider than narrow space. // This seems like a decent idea for a default for all formats. return 10;
1,260
48
1,308
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/UPCAReader.java
UPCAReader
maybeReturnResult
class UPCAReader extends UPCEANReader { private final UPCEANReader ean13Reader = new EAN13Reader(); @Override public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException, ChecksumException { return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, startGuardRange, hints)); } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException, ChecksumException { return maybeReturnResult(ean13Reader.decodeRow(rowNumber, row, hints)); } @Override public Result decode(BinaryBitmap image) throws NotFoundException, FormatException { return maybeReturnResult(ean13Reader.decode(image)); } @Override public Result decode(BinaryBitmap image, Map<DecodeHintType,?> hints) throws NotFoundException, FormatException { return maybeReturnResult(ean13Reader.decode(image, hints)); } @Override BarcodeFormat getBarcodeFormat() { return BarcodeFormat.UPC_A; } @Override protected int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException { return ean13Reader.decodeMiddle(row, startRange, resultString); } private static Result maybeReturnResult(Result result) throws FormatException {<FILL_FUNCTION_BODY>} }
String text = result.getText(); if (text.charAt(0) == '0') { Result upcaResult = new Result(text.substring(1), null, result.getResultPoints(), BarcodeFormat.UPC_A); if (result.getResultMetadata() != null) { upcaResult.putAllMetadata(result.getResultMetadata()); } return upcaResult; } else { throw FormatException.getFormatInstance(); }
428
122
550
<methods>public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException,public com.google.zxing.Result decodeRow(int, com.google.zxing.common.BitArray, int[], Map<com.google.zxing.DecodeHintType,?>) throws com.google.zxing.NotFoundException, com.google.zxing.ChecksumException, com.google.zxing.FormatException<variables>static final int[] END_PATTERN,static final non-sealed int[][] L_AND_G_PATTERNS,static final int[][] L_PATTERNS,private static final float MAX_AVG_VARIANCE,private static final float MAX_INDIVIDUAL_VARIANCE,static final int[] MIDDLE_PATTERN,static final int[] START_END_PATTERN,private final non-sealed java.lang.StringBuilder decodeRowStringBuffer,private final non-sealed com.google.zxing.oned.EANManufacturerOrgSupport eanManSupport,private final non-sealed com.google.zxing.oned.UPCEANExtensionSupport extensionReader
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/UPCAWriter.java
UPCAWriter
encode
class UPCAWriter implements Writer { private final EAN13Writer subWriter = new EAN13Writer(); @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType,?> hints) {<FILL_FUNCTION_BODY>} }
if (format != BarcodeFormat.UPC_A) { throw new IllegalArgumentException("Can only encode UPC-A, but got " + format); } // Transform a UPC-A code into the equivalent EAN-13 code and write it that way return subWriter.encode('0' + contents, BarcodeFormat.EAN_13, width, height, hints);
139
100
239
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/UPCEANExtension2Support.java
UPCEANExtension2Support
decodeRow
class UPCEANExtension2Support { private final int[] decodeMiddleCounters = new int[4]; private final StringBuilder decodeRowStringBuffer = new StringBuilder(); Result decodeRow(int rowNumber, BitArray row, int[] extensionStartRange) throws NotFoundException {<FILL_FUNCTION_BODY>} private int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException { int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; int checkParity = 0; for (int x = 0; x < 2 && rowOffset < end; x++) { int bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS); resultString.append((char) ('0' + bestMatch % 10)); for (int counter : counters) { rowOffset += counter; } if (bestMatch >= 10) { checkParity |= 1 << (1 - x); } if (x != 1) { // Read off separator if not last rowOffset = row.getNextSet(rowOffset); rowOffset = row.getNextUnset(rowOffset); } } if (resultString.length() != 2) { throw NotFoundException.getNotFoundInstance(); } if (Integer.parseInt(resultString.toString()) % 4 != checkParity) { throw NotFoundException.getNotFoundInstance(); } return rowOffset; } /** * @param raw raw content of extension * @return formatted interpretation of raw content as a {@link Map} mapping * one {@link ResultMetadataType} to appropriate value, or {@code null} if not known */ private static Map<ResultMetadataType,Object> parseExtensionString(String raw) { if (raw.length() != 2) { return null; } Map<ResultMetadataType,Object> result = new EnumMap<>(ResultMetadataType.class); result.put(ResultMetadataType.ISSUE_NUMBER, Integer.valueOf(raw)); return result; } }
StringBuilder result = decodeRowStringBuffer; result.setLength(0); int end = decodeMiddle(row, extensionStartRange, result); String resultString = result.toString(); Map<ResultMetadataType,Object> extensionData = parseExtensionString(resultString); Result extensionResult = new Result(resultString, null, new ResultPoint[] { new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0f, rowNumber), new ResultPoint(end, rowNumber), }, BarcodeFormat.UPC_EAN_EXTENSION); if (extensionData != null) { extensionResult.putAllMetadata(extensionData); } return extensionResult;
618
192
810
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/UPCEANExtension5Support.java
UPCEANExtension5Support
parseExtension5String
class UPCEANExtension5Support { private static final int[] CHECK_DIGIT_ENCODINGS = { 0x18, 0x14, 0x12, 0x11, 0x0C, 0x06, 0x03, 0x0A, 0x09, 0x05 }; private final int[] decodeMiddleCounters = new int[4]; private final StringBuilder decodeRowStringBuffer = new StringBuilder(); Result decodeRow(int rowNumber, BitArray row, int[] extensionStartRange) throws NotFoundException { StringBuilder result = decodeRowStringBuffer; result.setLength(0); int end = decodeMiddle(row, extensionStartRange, result); String resultString = result.toString(); Map<ResultMetadataType,Object> extensionData = parseExtensionString(resultString); Result extensionResult = new Result(resultString, null, new ResultPoint[] { new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0f, rowNumber), new ResultPoint(end, rowNumber), }, BarcodeFormat.UPC_EAN_EXTENSION); if (extensionData != null) { extensionResult.putAllMetadata(extensionData); } return extensionResult; } private int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException { int[] counters = decodeMiddleCounters; counters[0] = 0; counters[1] = 0; counters[2] = 0; counters[3] = 0; int end = row.getSize(); int rowOffset = startRange[1]; int lgPatternFound = 0; for (int x = 0; x < 5 && rowOffset < end; x++) { int bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS); resultString.append((char) ('0' + bestMatch % 10)); for (int counter : counters) { rowOffset += counter; } if (bestMatch >= 10) { lgPatternFound |= 1 << (4 - x); } if (x != 4) { // Read off separator if not last rowOffset = row.getNextSet(rowOffset); rowOffset = row.getNextUnset(rowOffset); } } if (resultString.length() != 5) { throw NotFoundException.getNotFoundInstance(); } int checkDigit = determineCheckDigit(lgPatternFound); if (extensionChecksum(resultString.toString()) != checkDigit) { throw NotFoundException.getNotFoundInstance(); } return rowOffset; } private static int extensionChecksum(CharSequence s) { int length = s.length(); int sum = 0; for (int i = length - 2; i >= 0; i -= 2) { sum += s.charAt(i) - '0'; } sum *= 3; for (int i = length - 1; i >= 0; i -= 2) { sum += s.charAt(i) - '0'; } sum *= 3; return sum % 10; } private static int determineCheckDigit(int lgPatternFound) throws NotFoundException { for (int d = 0; d < 10; d++) { if (lgPatternFound == CHECK_DIGIT_ENCODINGS[d]) { return d; } } throw NotFoundException.getNotFoundInstance(); } /** * @param raw raw content of extension * @return formatted interpretation of raw content as a {@link Map} mapping * one {@link ResultMetadataType} to appropriate value, or {@code null} if not known */ private static Map<ResultMetadataType,Object> parseExtensionString(String raw) { if (raw.length() != 5) { return null; } Object value = parseExtension5String(raw); if (value == null) { return null; } Map<ResultMetadataType,Object> result = new EnumMap<>(ResultMetadataType.class); result.put(ResultMetadataType.SUGGESTED_PRICE, value); return result; } private static String parseExtension5String(String raw) {<FILL_FUNCTION_BODY>} }
String currency; switch (raw.charAt(0)) { case '0': currency = "£"; break; case '5': currency = "$"; break; case '9': // Reference: http://www.jollytech.com switch (raw) { case "90000": // No suggested retail price return null; case "99991": // Complementary return "0.00"; case "99990": return "Used"; } // Otherwise... unknown currency? currency = ""; break; default: currency = ""; break; } int rawAmount = Integer.parseInt(raw.substring(1)); String unitsString = String.valueOf(rawAmount / 100); int hundredths = rawAmount % 100; String hundredthsString = hundredths < 10 ? "0" + hundredths : String.valueOf(hundredths); return currency + unitsString + '.' + hundredthsString;
1,176
274
1,450
<no_super_class>
zxing_zxing
zxing/core/src/main/java/com/google/zxing/oned/UPCEANExtensionSupport.java
UPCEANExtensionSupport
decodeRow
class UPCEANExtensionSupport { private static final int[] EXTENSION_START_PATTERN = {1,1,2}; private final UPCEANExtension2Support twoSupport = new UPCEANExtension2Support(); private final UPCEANExtension5Support fiveSupport = new UPCEANExtension5Support(); Result decodeRow(int rowNumber, BitArray row, int rowOffset) throws NotFoundException {<FILL_FUNCTION_BODY>} }
int[] extensionStartRange = UPCEANReader.findGuardPattern(row, rowOffset, false, EXTENSION_START_PATTERN); try { return fiveSupport.decodeRow(rowNumber, row, extensionStartRange); } catch (ReaderException ignored) { return twoSupport.decodeRow(rowNumber, row, extensionStartRange); }
117
92
209
<no_super_class>