id
stringlengths
7
14
text
stringlengths
1
37.2k
246774970_0
public static String doPost(String urlStr, List<BasicHeader> headers) { return doExecute(urlStr, new HttpPost(check(urlStr)), headers); }
247595825_0
@Bean @ConditionalOnMissingBean @ConditionalOnAvailableEndpoint public RedisDescribeAvailableResourceEndpoint redisDescribeAvailableResourceEndpoint() { return new RedisDescribeAvailableResourceEndpoint(aliCloudProperties, redisProperties); }
248283523_3
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public RegionsDto getAllRegions() { LOGGER.info("REGION GET ALL API"); var allRegions = service.getAllRegions(); var dtoList = new ArrayList<RegionDto>(); allRegions.forEach(region -> { var dto = new RegionDto(region); dtoList.add(dto); }); var regionsDto = new RegionsDto(dtoList); return regionsDto; }
248529016_1
public static boolean isRetryHandlerMethod(Class<?> targetClass, Method method) { if ("handle".equals(method.getName()) && method.getParameterCount() == 1 && method.isBridge() && method.isSynthetic()) { //RetryHandler接口有泛型,需要特殊处理 return true; } Type interfaceType = getRetryHandlerGenericInterface(targetClass); if (interfaceType == null) { return false; } Class<?> argsInputType = Object.class; if (interfaceType instanceof ParameterizedType) { argsInputType = (Class<?>) ((ParameterizedType) interfaceType).getActualTypeArguments()[0]; } Class<?> parameterType = argsInputType; return "handle".equals(method.getName()) && method.getParameterCount() == 1 && method.getParameterTypes()[0].equals(parameterType); }
248826224_5
public ISBN getIsbn() { return isbn; }
248828585_8
public boolean validateToken(String authToken) { try { Jwts.parser().setSigningKey(key).parseClaimsJws(authToken); return true; } catch (JwtException | IllegalArgumentException e) { log.info("Invalid JWT token."); log.trace("Invalid JWT token trace.", e); } return false; }
249609964_0
public static boolean checkFileExists(String file) { Path path = Paths.get(file); if (Files.exists(path)) { return true; } return false; }
249842163_0
public static MessageSizeResponse parse(JSONObject obj) throws JSONException { MessageSizeResponse response = new MessageSizeResponse(); if (obj.has("sizeOfQueryResponse")) { response.sizeOfQueryResponse = obj.getInt("sizeOfQueryResponse"); } return response; }
250091476_0
static String getPrincipalFromKeytab(String keytabLocation) { try { return Keytab .read(new File(keytabLocation)) .getEntries().get(0) .getPrincipalName() .split("@")[0] .replace('\\', '/'); } catch (Exception ex) { throw new TokenServiceException(ex.getMessage(), ErrorCode.READ_KEYTAB_EXCEPTION); } }
250721746_0
@Async("gitCloneExecutor") public void clone(GitInfo gitInfo) { log.debug("开始clone,git信息[{}]", gitInfo); //创建临时文件夹 Path tempDirectory; try { tempDirectory = Files.createTempDirectory(gitProxyProperties.getTempDirPath(), gitInfo.getRepositoryName()); } catch (IOException e) { throw new GitProxyException("创建临时文件夹失败!", e); } String tempDirectoryPath = tempDirectory.toString(); //clone项目到临时文件夹 CommandResult result; try { result = CommandUtils.getResult("git clone " + gitInfo.getUrl(), tempDirectoryPath); } catch (ExecutionException e) { throw new GitProxyException("clone命令执行失败!", e); } catch (InterruptedException e) { throw new GitProxyException("clone操作中断!", e); } Assert.isTrue(CommandUtils.verify(result), result.getResult()); //将项目打压缩包 ZipUtil.zip(tempDirectoryPath, gitProxyProperties.getZipFilePath() + "\\" + tempDirectory.getFileName() + ".zip"); }
251049092_17
@Override public List<WeatherCondition> getConditions() { return Collections.unmodifiableList(new ArrayList<WeatherCondition>(this.conditions)); }
251068401_3
public static DateTime withStartOfQuarter(DateTime dateTime) { int monthOfYear = dateTime.getMonthOfYear(); DateTime firstMonthOfQuarter; if (monthOfYear >= DateTimeConstants.OCTOBER) { firstMonthOfQuarter = dateTime.withMonthOfYear(DateTimeConstants.OCTOBER); } else if (monthOfYear >= DateTimeConstants.JULY) { firstMonthOfQuarter = dateTime.withMonthOfYear(DateTimeConstants.JULY); } else if (monthOfYear >= DateTimeConstants.APRIL) { firstMonthOfQuarter = dateTime.withMonthOfYear(DateTimeConstants.APRIL); } else { firstMonthOfQuarter = dateTime.withMonthOfYear(DateTimeConstants.JANUARY); } return firstMonthOfQuarter.withDayOfMonth(1); }
251477582_0
public BigDecimal getBalance(String address) { List<UTXO> unspent = this.getUnspent(Arrays.asList(address)); Long balance = 0L; for (UTXO utxo : unspent) { balance = balance + utxo.getValue().value; } logger.info(unspent.toString()); return new BigDecimal(balance / 100000000.0).setScale(8, BigDecimal.ROUND_DOWN); }
252293371_1
public static void generateAllTCNsFromReport(byte[] report, INextTCNCallback callback) { int from = readUShort(report, 64); byte[] bstartTCK = Arrays.copyOfRange(report, 32, 64); TCNProtoGen ratchet = new TCNProtoGen(report[68], getRvkfromReport(report), bstartTCK, from - 1); int to = readUShort(report, 66); callback.next(ratchet.getCurrentTCN()); for (int i = from; i < to; i++) { callback.next(ratchet.getNewTCN()); } }
252902347_4
@Override public void onApplicationEvent(WebServerInitializedEvent event) { File portFile = getPortFile(event.getApplicationContext()); try { String port = String.valueOf(event.getWebServer().getPort()); createParentFolder(portFile); FileCopyUtils.copy(port.getBytes(), portFile); portFile.deleteOnExit(); } catch (Exception ex) { logger.warn(String.format("Cannot create port file %s", this.file)); } }
253269900_126
List<Atom> getAtomList() { return new ArrayList<Atom>(atomCollection); }
253595061_79
public String validate() { List<String> validationIssues = new LinkedList<>(); if(maximumExecutionSeconds < 0) validationIssues.add("maximumExecutionSeconds must be non-negative"); return validationIssues.size() == 0 ? null : String.join(",", validationIssues); }
254264048_0
public static ASTNode parse(final String sql) { ParseTree parseTree = createParseTree(sql); return new SQLVisitor().visit(parseTree.getChild(0)); }
255469961_50
@ExceptionHandler(RuntimeException.class) public ResponseEntity<Object> handleRuntimeException(RuntimeException exception) { return new ResponseEntity<>(createResponseBody(exception.getMessage(), BAD_REQUEST), new HttpHeaders(), BAD_REQUEST); }
255633533_25
static List<ExecutionNode> sort(List<ExecutionNode> nodes) { // priority is initial order in the list, node earlier in the list // would be always executed earlier if possible Map<String, Integer> priorityMap = new HashMap<>(); Map<String, Integer> degreeMap = new HashMap<>(); Map<String, ExecutionNode> lookup = new HashMap<>(); ListMultimap<String, String> downstreamNodeIdsMap = ArrayListMultimap.create(); for (int i = 0; i < nodes.size(); i++) { ExecutionNode node = nodes.get(i); priorityMap.put(node.nodeId(), i); degreeMap.put(node.nodeId(), node.upstreamNodeIds().size()); for (String upstreamNodeId : node.upstreamNodeIds()) { downstreamNodeIdsMap.put(upstreamNodeId, node.nodeId()); } ExecutionNode previous = lookup.put(node.nodeId(), node); Verify.verify(previous == null, "duplicate node id [%s]", node.nodeId()); } Deque<List<String>> deque = new ArrayDeque<>(); Set<String> visitedNodeIds = new HashSet<>(); List<ExecutionNode> topologicallySorted = new ArrayList<>(); deque.add(singletonList(START_NODE_ID)); while (!deque.isEmpty()) { List<String> nodeIds = deque.pollFirst(); List<String> downstreamNodeIds = new ArrayList<>(); for (String nodeId : nodeIds) { if (!nodeId.equals(START_NODE_ID)) { ExecutionNode node = lookup.get(nodeId); Verify.verifyNotNull(node, "node not found [%s]", nodeId); topologicallySorted.add(node); } boolean visited = visitedNodeIds.contains(nodeId); Verify.verify(!visited, "invariant failed"); for (String downstreamNodeId : downstreamNodeIdsMap.get(nodeId)) { int newDegree = degreeMap.get(downstreamNodeId) - 1; if (newDegree == 0) { downstreamNodeIds.add(downstreamNodeId); } degreeMap.put(downstreamNodeId, newDegree); } } visitedNodeIds.addAll(nodeIds); // traverse each batch of nodes in priority order if (!downstreamNodeIds.isEmpty()) { List<String> sortedDownstreamNodeIds = downstreamNodeIds.stream() .sorted(Comparator.comparing(priorityMap::get)) .distinct() .collect(Collectors.toList()); deque.push(sortedDownstreamNodeIds); } } Verify.verify( nodes.size() == topologicallySorted.size(), "workflow graph isn't connected or has a cycle"); return topologicallySorted; }
256285632_3
@Override public void stopScans(@NonNull ScanCallback scanCallback) { try { if (!bluetoothAdapter.isEnabled()) { BeaconLogger.e( "Can't stop the BLE scans since BluetoothAdapter is not enabled, most likely " + "the scans weren't started either (check if Bluetooth is turned on)" ); return; } final BluetoothLeScanner bleScanner = bluetoothAdapter.getBluetoothLeScanner(); if (bleScanner == null) { BeaconLogger.e( "Can't stop the BLE scans since there is no BluetoothLeScanner available, " + "most likely the scans weren't started either (check if Bluetooth is " + "turned on)" ); return; } bleScanner.stopScan(scanCallback); } catch (SecurityException e) { BeaconLogger.e( "Can't stop the BLE scans since it results in SecurityException (check if the " + "is running in the Samsung's Knox container or something similar)" ); } }
257682134_30
public static String createHash(String password, String salt, int iterations, int dkLen) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] saltBytes = salt.getBytes(StandardCharsets.UTF_8); byte[] hash = pbkdf2(password.toCharArray(), saltBytes, iterations, dkLen); return toHex(hash); }
259639325_11
public void setOnCoord(Object value, int... coords) { checkCoordsLength(coords); if (value != null) { if (this.isScalar()) { this.data = value; } else if (value.getClass().isArray()) { this.setArrayOnCoord(value, coords); } else { this.setSingleOnCoord(value, coords); } } }
259929534_5
@DeleteMapping() public ResponseEntity<Book> deleteAll() { LOGGER.info("Delete all books"); books.clear(); return ResponseEntity.noContent().build(); }
260172508_9
@Override public void close() { if (!isClosed.compareAndSet(false, true)) { return; } // unmap and close file for (Tuple2<RandomAccessFile, MappedByteBuffer> tuple : memoryMappedFiles) { PlatformDependent.freeDirectBuffer(tuple.f1); IOUtils.closeQuietly(tuple.f0); } // cleanup directories removeCandidateDirectory(candidateDirectories); }
261970003_3
public <T> T query(final String baseQuery, final ResultSetHandler<T> resultHandler, final Object... params) throws SQLException { try { return this.queryRunner.query(baseQuery, resultHandler, params); } catch (final SQLException ex) { // todo kunkun-tang: Retry logics should be implemented here. logger.error("query failed", ex); if (this.dbMetrics != null) { this.dbMetrics.markDBFailQuery(); } throw ex; } }
263047969_22
@MainThread public void restoreState(@NonNull S state) { store.restoreState(state); }
263923665_38
public int calculateNOC(String filepath, String analyzerType) throws IOException { if(analyzerType.equals("regex")) { String sourceCode = fileReader.readFileIntoString(filepath); Pattern pattern = Pattern.compile(".*\\s*class\\s+.*"); Matcher classSignatures = pattern.matcher(sourceCode); int classCounter = 0; while (classSignatures.find()) { classCounter++; } return classCounter; } else if (analyzerType.equals("strcomp")) { List<String> sourceCodeList = fileReader.readFileIntoList(filepath); int classCounter = 0; for (String line : sourceCodeList) { line = line.trim(); //remove leading and trailing white spaces if ((line.startsWith("class ") || line.contains(" class ")) && line.contains("{")) { classCounter++; } } return classCounter; } return -1; }
264141019_7
@Override protected Stream<DataPoint> streamDataPoints() { return Utils.getStream(nRows) .mapToObj(this::mapIndexToDataPoint); }
264503046_2
@Nullable protected T initClass() { T instance = null; try { final Constructor<T> constructor = getClazz().getDeclaredConstructor(); constructor.setAccessible(true); instance = constructor.newInstance(); } catch (NoSuchMethodException e) { getLogger().log(Level.SEVERE, e, () -> "Couldn't find the default constructor for the class " + clazz.getSimpleName()); } catch (IllegalAccessException | InstantiationException e) { getLogger().log(Level.SEVERE, e, () -> "Failed to initialize the class " + clazz.getSimpleName()); } catch (InvocationTargetException e) { getLogger().log(Level.SEVERE, e.getCause(), () -> "An exception was thrown when trying to initialize the class " + clazz.getSimpleName()); } return instance; }
265127043_6
public static void PKCS10CertificationRequest2File(PKCS10CertificationRequest request, FileOutputStream stream) { JcaPEMWriter jcaPEMWriter = new JcaPEMWriter(new OutputStreamWriter(stream)); try { jcaPEMWriter.writeObject(request); jcaPEMWriter.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { jcaPEMWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
265243047_3
public static String convertRegularExpr (String str) { if(str == null){ return ""; } String pattern = "\\\\(\\d{3})"; Pattern r = Pattern.compile(pattern); while(true) { Matcher m = r.matcher(str); if(!m.find()) { break; } String num = m.group(1); int x = Integer.parseInt(num, 8); str = m.replaceFirst(String.valueOf((char)x)); } str = str.replaceAll("\\\\t","\t"); str = str.replaceAll("\\\\r","\r"); str = str.replaceAll("\\\\n","\n"); return str; }
265564812_1
@SneakyThrows public void destroy() { server.stop(); server.destroy(); }
266285061_0
@Override public ResponseEntity<BlueprintResponse> get(String key) { return ResponseEntity.ok(blueprintService.get(key)); }
266937709_0
public static List<SearchJDResultDTO> parseJd(String keyword) { try { String url = "https://search.jd.com/Search?keyword=" + URLEncoder.encode(keyword, CharsetKit.UTF_8); Document document = Jsoup.connect(url).timeout(5 * 1000).get(); Element elementById = document.getElementById("J_goodsList"); Elements elements = elementById.getElementsByTag("li"); ArrayList<SearchJDResultDTO> list = Lists.newArrayList(); for (Element element : elements) { String img = element.getElementsByTag("img").eq(0).attr("src"); if (img == null) { img = element.getElementsByTag("img").eq(0).attr("source-data-lazy-img"); } String price = element.getElementsByClass("p-price").eq(0).text(); String title = element.getElementsByClass("p-name").eq(0).text(); SearchJDResultDTO searchJDResultDTO = new SearchJDResultDTO(img, price, title); list.add(searchJDResultDTO); } return list; } catch (IOException e) { e.printStackTrace(); throw new BaseException(ResultCode.PARAMETER_INVALID, ResultCode.MSG_PARAMETER_INVALID); } }
267134885_4
public PanacheQuery<User> findByFirstName(final String firstName) { return find("firstName", firstName); }
267999301_0
public Document getXmlDocument() { return xmlDocument; }
269759605_7
public void setColumns(int columns) { this.columns = columns; }
271229375_1
public static Time toTime(String s) { try { return new Time(StdDateFormat.getTimeInstance().parse(s).getTime()); } catch (ParseException e) { throw new IllegalArgumentException(s); } }
276117258_29
public static List<NativeQuery> parseJdbcSql(String query, boolean standardConformingStrings, boolean withParameters, boolean splitStatements, boolean isBatchedReWriteConfigured, String... returningColumnNames) throws SQLException { int numOfOverSymble = 0; boolean haveProcedure = false; boolean haveFunction = false; if(startWithComment(query)) { query = removeFirstComment(query); } String reg = "\\s+"; String queryTemp = query.trim(); queryTemp = queryTemp.replaceAll(reg, "\0"); String[] queryArr = queryTemp.split("\0"); for(int i = 0;i < queryArr.length; i++) { if (queryArr[i] != null && (queryArr[i].toUpperCase(Locale.ENGLISH)).equals("PROCEDURE") ) { haveProcedure = true; } if (queryArr[i] != null && (queryArr[i].toUpperCase(Locale.ENGLISH)).equals("FUNCTION") ) { haveFunction = true; } } if (!withParameters && !splitStatements && returningColumnNames != null && returningColumnNames.length == 0) { return Collections.singletonList(new NativeQuery(query, SqlCommand.createStatementTypeInfo(SqlCommandType.BLANK))); } int fragmentStart = 0; int inParen = 0; int inBeginEnd = 0; char[] aChars = query.toCharArray(); StringBuilder nativeSql = new StringBuilder(query.length() + 10); List<Integer> bindPositions = null; // initialized on demand List<NativeQuery> nativeQueries = null; boolean isCurrentReWriteCompatible = false; boolean isValuesFound = false; int valuesBraceOpenPosition = -1; int valuesBraceClosePosition = -1; boolean valuesBraceCloseFound = false; boolean isInsertPresent = false; boolean isReturningPresent = false; boolean isReturningPresentPrev = false; SqlCommandType currentCommandType = SqlCommandType.BLANK; SqlCommandType prevCommandType = SqlCommandType.BLANK; int numberOfStatements = 0; boolean whitespaceOnly = true; int keyWordCount = 0; int keywordStart = -1; int keywordEnd = -1; for (int i = 0; i < aChars.length; ++i) { char aChar = aChars[i]; boolean isKeyWordChar = false; // ';' is ignored as it splits the queries whitespaceOnly &= aChar == ';' || Character.isWhitespace(aChar); keywordEnd = i; // parseSingleQuotes, parseDoubleQuotes, etc move index so we keep old value switch (aChar) { case '\'': // single-quotes i = Parser.parseSingleQuotes(aChars, i, standardConformingStrings); break; case '"': // double-quotes i = Parser.parseDoubleQuotes(aChars, i); break; case '-': // possibly -- style comment i = Parser.parseLineComment(aChars, i); break; case '/': // possibly /* */ style comment int j = i; i = Parser.parseBlockComment(aChars, i); if(j != i) { break; } if (i < aChars.length - 1 && "*".equals(String.valueOf(aChars[i + 1]))) { break; } if (i >1 && "*".equals(String.valueOf(aChars[i - 1] ))) { break; } if (inBeginEnd > 0) { break; } if (i >1 && "\n".equals(String.valueOf(aChars[i - 1]))) { numOfOverSymble++; if (inParen == 0) { if (!whitespaceOnly) { numberOfStatements++; nativeSql.append(aChars, fragmentStart, i - fragmentStart); whitespaceOnly = true; } fragmentStart = i + 1; if (nativeSql.length() > 0) { if (addReturning( nativeSql, currentCommandType, returningColumnNames, isReturningPresent)) { isReturningPresent = true; } if (splitStatements) { if (nativeQueries == null) { nativeQueries = new ArrayList<NativeQuery>(); } if (!isValuesFound || !isCurrentReWriteCompatible || valuesBraceClosePosition == -1 || (bindPositions != null && valuesBraceClosePosition < bindPositions.get(bindPositions.size() - 1))) { valuesBraceOpenPosition = -1; valuesBraceClosePosition = -1; } nativeQueries.add( new NativeQuery( nativeSql.toString(), toIntArray(bindPositions), false, SqlCommand.createStatementTypeInfo( currentCommandType, isBatchedReWriteConfigured, valuesBraceOpenPosition, valuesBraceClosePosition, isReturningPresent, nativeQueries.size()))); } } prevCommandType = currentCommandType; isReturningPresentPrev = isReturningPresent; currentCommandType = SqlCommandType.BLANK; isReturningPresent = false; if (splitStatements) { // Prepare for next query if (bindPositions != null) { bindPositions.clear(); } nativeSql.setLength(0); isValuesFound = false; isCurrentReWriteCompatible = false; valuesBraceOpenPosition = -1; valuesBraceClosePosition = -1; valuesBraceCloseFound = false; } } break; } case '$': // possibly dollar quote start i = Parser.parseDollarQuotes(aChars, i); break; // case '(' moved below to parse "values(" properly case ')': inParen--; if (inParen == 0 && isValuesFound && !valuesBraceCloseFound) { // If original statement is multi-values like VALUES (...), (...), ... then // search for the latest closing paren valuesBraceClosePosition = nativeSql.length() + i - fragmentStart; } break; case '?': nativeSql.append(aChars, fragmentStart, i - fragmentStart); if (i + 1 < aChars.length && aChars[i + 1] == '?') /* replace ?? with ? */ { nativeSql.append('?'); i++; // make sure the coming ? is not treated as a bind } else { if (!withParameters) { nativeSql.append('?'); } else { if (bindPositions == null) { bindPositions = new ArrayList<Integer>(); } bindPositions.add(nativeSql.length()); int bindIndex = bindPositions.size(); nativeSql.append(NativeQuery.bindName(bindIndex)); } } fragmentStart = i + 1; break; case ';': if (haveProcedure || haveFunction) { break; } if (queryArr[0] !=null && ((queryArr[0].toUpperCase(Locale.ENGLISH)).equals("BEGIN") ||(queryArr[0].toUpperCase(Locale.ENGLISH)).equals("DECLARE"))) { break; } if (inParen == 0) { if (!whitespaceOnly) { numberOfStatements++; nativeSql.append(aChars, fragmentStart, i - fragmentStart); whitespaceOnly = true; } fragmentStart = i + 1; if (nativeSql.length() > 0) { if (addReturning(nativeSql, currentCommandType, returningColumnNames, isReturningPresent)) { isReturningPresent = true; } if (splitStatements) { if (nativeQueries == null) { nativeQueries = new ArrayList<NativeQuery>(); } if (!isValuesFound || !isCurrentReWriteCompatible || valuesBraceClosePosition == -1 || (bindPositions != null && valuesBraceClosePosition < bindPositions.get(bindPositions.size() - 1))) { valuesBraceOpenPosition = -1; valuesBraceClosePosition = -1; } nativeQueries.add(new NativeQuery(nativeSql.toString(), toIntArray(bindPositions), false, SqlCommand.createStatementTypeInfo( currentCommandType, isBatchedReWriteConfigured, valuesBraceOpenPosition, valuesBraceClosePosition, isReturningPresent, nativeQueries.size()))); } } prevCommandType = currentCommandType; isReturningPresentPrev = isReturningPresent; currentCommandType = SqlCommandType.BLANK; isReturningPresent = false; if (splitStatements) { // Prepare for next query if (bindPositions != null) { bindPositions.clear(); } nativeSql.setLength(0); isValuesFound = false; isCurrentReWriteCompatible = false; valuesBraceOpenPosition = -1; valuesBraceClosePosition = -1; valuesBraceCloseFound = false; } } break; case 'b': case 'B': if(i + 4 < aChars.length) { if ("E".equalsIgnoreCase(String.valueOf(aChars[i + 1])) && "G".equalsIgnoreCase(String.valueOf(aChars[i + 2])) && "I".equalsIgnoreCase(String.valueOf(aChars[i + 3])) && "N".equalsIgnoreCase(String.valueOf(aChars[i + 4]))) { inBeginEnd ++; } } break; case 'e': case 'E': if (i + 2 < aChars.length) { if ("N".equalsIgnoreCase(String.valueOf(aChars[i + 1])) && "D".equalsIgnoreCase(String.valueOf(aChars[i + 2]))) { inBeginEnd --; } } default: if (keywordStart >= 0) { // When we are inside a keyword, we need to detect keyword end boundary // Note that isKeyWordChar is initialized to false before the switch, so // all other characters would result in isKeyWordChar=false isKeyWordChar = isIdentifierContChar(aChar); break; } // Not in keyword, so just detect next keyword start isKeyWordChar = isIdentifierStartChar(aChar); if (isKeyWordChar) { keywordStart = i; if (valuesBraceOpenPosition != -1 && inParen == 0) { // When the statement already has multi-values, stop looking for more of them // Since values(?,?),(?,?),... should not contain keywords in the middle valuesBraceCloseFound = true; } } break; } if (keywordStart >= 0 && (i == aChars.length - 1 || !isKeyWordChar)) { int wordLength = (isKeyWordChar ? i + 1 : keywordEnd) - keywordStart; if (currentCommandType == SqlCommandType.BLANK) { if (wordLength == 6 && parseUpdateKeyword(aChars, keywordStart)) { currentCommandType = SqlCommandType.UPDATE; } else if (wordLength == 6 && parseDeleteKeyword(aChars, keywordStart)) { currentCommandType = SqlCommandType.DELETE; } else if (wordLength == 4 && parseMoveKeyword(aChars, keywordStart)) { currentCommandType = SqlCommandType.MOVE; } else if (wordLength == 6 && parseSelectKeyword(aChars, keywordStart)) { currentCommandType = SqlCommandType.SELECT; } else if (wordLength == 4 && parseWithKeyword(aChars, keywordStart)) { currentCommandType = SqlCommandType.WITH; } else if (wordLength == 6 && parseInsertKeyword(aChars, keywordStart)) { if (!isInsertPresent && (nativeQueries == null || nativeQueries.isEmpty())) { // Only allow rewrite for insert command starting with the insert keyword. // Else, too many risks of wrong interpretation. isCurrentReWriteCompatible = keyWordCount == 0; isInsertPresent = true; currentCommandType = SqlCommandType.INSERT; } else { isCurrentReWriteCompatible = false; } } } else if (currentCommandType == SqlCommandType.WITH && inParen == 0) { SqlCommandType command = parseWithCommandType(aChars, i, keywordStart, wordLength); if (command != null) { currentCommandType = command; } } if (inParen != 0 || aChar == ')') { // RETURNING and VALUES cannot be present in braces } else if (wordLength == 9 && parseReturningKeyword(aChars, keywordStart)) { isReturningPresent = true; } else if (wordLength == 6 && parseValuesKeyword(aChars, keywordStart)) { isValuesFound = true; } keywordStart = -1; keyWordCount++; } if (aChar == '(') { inParen++; if (inParen == 1 && isValuesFound && valuesBraceOpenPosition == -1) { valuesBraceOpenPosition = nativeSql.length() + i - fragmentStart; } } } if (!isValuesFound || !isCurrentReWriteCompatible || valuesBraceClosePosition == -1 || (bindPositions != null && valuesBraceClosePosition < bindPositions.get(bindPositions.size() - 1))) { valuesBraceOpenPosition = -1; valuesBraceClosePosition = -1; } if (fragmentStart < aChars.length && !whitespaceOnly) { nativeSql.append(aChars, fragmentStart, aChars.length - fragmentStart); } else { if (numberOfStatements > 1) { isReturningPresent = false; currentCommandType = SqlCommandType.BLANK; } else if (numberOfStatements == 1) { isReturningPresent = isReturningPresentPrev; currentCommandType = prevCommandType; } } if (nativeSql.length() == 0) { return nativeQueries != null ? nativeQueries : Collections.<NativeQuery>emptyList(); } if (addReturning(nativeSql, currentCommandType, returningColumnNames, isReturningPresent)) { isReturningPresent = true; } NativeQuery lastQuery = new NativeQuery(nativeSql.toString(), toIntArray(bindPositions), !splitStatements, SqlCommand.createStatementTypeInfo(currentCommandType, isBatchedReWriteConfigured, valuesBraceOpenPosition, valuesBraceClosePosition, isReturningPresent, (nativeQueries == null ? 0 : nativeQueries.size()))); if (nativeQueries == null) { return Collections.singletonList(lastQuery); } if (!whitespaceOnly) { nativeQueries.add(lastQuery); } return nativeQueries; }