code
stringlengths
73
34.1k
label
stringclasses
1 value
protected void setInputElementValue(Node element, FormInput input) { LOGGER.debug("INPUTFIELD: {} ({})", input.getIdentification(), input.getType()); if (element == null || input.getInputValues().isEmpty()) { return; } try { switch (input.getType()) { case TEXT: case TEXTAREA: case PASSWORD:...
java
private void handleHidden(FormInput input) { String text = input.getInputValues().iterator().next().getValue(); if (null == text || text.length() == 0) { return; } WebElement inputElement = browser.getWebElement(input.getIdentification()); JavascriptExecutor js = (JavascriptExecutor) browser.getWebDriver()...
java
@Override public EmbeddedBrowser get() { LOGGER.debug("Setting up a Browser"); // Retrieve the config values used ImmutableSortedSet<String> filterAttributes = configuration.getCrawlRules().getPreCrawlConfig().getFilterAttributeNames(); long crawlWaitReload = configuration.getCrawlRules().getWaitAfterReloa...
java
public StackTraceElement[] asStackTrace() { int i = 1; StackTraceElement[] list = new StackTraceElement[this.size()]; for (Eventable e : this) { list[this.size() - i] = new StackTraceElement(e.getEventType().toString(), e.getIdentification() .toString(), e.getElement().toString(), i); i++; } ...
java
public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl, ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent, long crawlWaitReload) { return WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl), filterAttributes, crawlWaitEvent, crawlWaitReload); }
java
public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver, ImmutableSortedSet<String> filterAttributes, long crawlWaitEvent, long crawlWaitReload) { return new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent, crawlWaitReload); }
java
private static RemoteWebDriver buildRemoteWebDriver(String hubUrl) { DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setPlatform(Platform.ANY); URL url; try { url = new URL(hubUrl); } catch (MalformedURLException e) { LOGGER.error("The given hub url of the remote server is mal...
java
@Override public void handlePopups() { /* * try { executeJavaScript("window.alert = function(msg){return true;};" + * "window.confirm = function(msg){return true;};" + * "window.prompt = function(msg){return true;};"); } catch (CrawljaxException e) { * LOGGER.error("Handling of PopUp windows failed", e);...
java
private boolean fireEventWait(WebElement webElement, Eventable eventable) throws ElementNotVisibleException, InterruptedException { switch (eventable.getEventType()) { case click: try { webElement.click(); } catch (ElementNotVisibleException e) { throw e; } catch (WebDriverException e) { ...
java
private String filterAttributes(String html) { String filteredHtml = html; for (String attribute : this.filterAttributes) { String regex = "\\s" + attribute + "=\"[^\"]*\""; Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(html); filteredHtml = m.replaceAll(""); } ...
java
@Override public synchronized boolean fireEventAndWait(Eventable eventable) throws ElementNotVisibleException, NoSuchElementException, InterruptedException { try { boolean handleChanged = false; boolean result = false; if (eventable.getRelatedFrame() != null && !eventable.getRelatedFrame().equals("")) ...
java
@Override public Object executeJavaScript(String code) throws CrawljaxException { try { JavascriptExecutor js = (JavascriptExecutor) browser; return js.executeScript(code); } catch (WebDriverException e) { throwIfConnectionException(e); throw new CrawljaxException(e); } }
java
private InputValue getInputValue(FormInput input) { /* Get the DOM element from Selenium. */ WebElement inputElement = browser.getWebElement(input.getIdentification()); switch (input.getType()) { case TEXT: case PASSWORD: case HIDDEN: case SELECT: case TEXTAREA: return new InputValue(inputEle...
java
public static Properties loadProps(String filename) { Properties props = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(filename); props.load(fis); return props; } catch (IOException ex) { throw new RuntimeExc...
java
public static Properties getProps(Properties props, String name, Properties defaultProperties) { final String propString = props.getProperty(name); if (propString == null) return defaultProperties; String[] propValues = propString.split(","); if (propValues.length < 1) { thro...
java
public static String getString(Properties props, String name, String defaultValue) { return props.containsKey(name) ? props.getProperty(name) : defaultValue; }
java
public static int read(ReadableByteChannel channel, ByteBuffer buffer) throws IOException { int count = channel.read(buffer); if (count == -1) throw new EOFException("Received -1 when reading from channel, socket has likely been closed."); return count; }
java
public static void writeShortString(ByteBuffer buffer, String s) { if (s == null) { buffer.putShort((short) -1); } else if (s.length() > Short.MAX_VALUE) { throw new IllegalArgumentException("String exceeds the maximum size of " + Short.MAX_VALUE + "."); } else { ...
java
public static void putUnsignedInt(ByteBuffer buffer, int index, long value) { buffer.putInt(index, (int) (value & 0xffffffffL)); }
java
public static long crc32(byte[] bytes, int offset, int size) { CRC32 crc = new CRC32(); crc.update(bytes, offset, size); return crc.getValue(); }
java
public static Thread newThread(String name, Runnable runnable, boolean daemon) { Thread thread = new Thread(runnable, name); thread.setDaemon(daemon); return thread; }
java
private static void unregisterMBean(String name) { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { synchronized (mbs) { ObjectName objName = new ObjectName(name); if (mbs.isRegistered(objName)) { mbs.unregisterMBean(objN...
java
@SuppressWarnings("resource") public static FileChannel openChannel(File file, boolean mutable) throws IOException { if (mutable) { return new RandomAccessFile(file, "rw").getChannel(); } return new FileInputStream(file).getChannel(); }
java
@SuppressWarnings("unchecked") public static <E> E getObject(String className) { if (className == null) { return (E) null; } try { return (E) Class.forName(className).newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e)...
java
public static String md5(byte[] source) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(source); byte tmp[] = md.digest(); char str[] = new char[32]; int k = 0; for (byte b : tmp) { str[k++] = hexDigit...
java
public void append(LogSegment segment) { while (true) { List<LogSegment> curr = contents.get(); List<LogSegment> updated = new ArrayList<LogSegment>(curr); updated.add(segment); if (contents.compareAndSet(curr, updated)) { return; } ...
java
public List<LogSegment> trunc(int newStart) { if (newStart < 0) { throw new IllegalArgumentException("Starting index must be positive."); } while (true) { List<LogSegment> curr = contents.get(); int newLength = Math.max(curr.size() - newStart, 0); ...
java
public LogSegment getLastView() { List<LogSegment> views = getView(); return views.get(views.size() - 1); }
java
private void cleanupLogs() throws IOException { logger.trace("Beginning log cleanup..."); int total = 0; Iterator<Log> iter = getLogIterator(); long startMs = System.currentTimeMillis(); while (iter.hasNext()) { Log log = iter.next(); total += cleanupExpir...
java
private int cleanupSegmentsToMaintainSize(final Log log) throws IOException { if (logRetentionSize < 0 || log.size() < logRetentionSize) return 0; List<LogSegment> toBeDeleted = log.markDeletedWhile(new LogSegmentFilter() { long diff = log.size() - logRetentionSize; public boo...
java
private int deleteSegments(Log log, List<LogSegment> segments) { int total = 0; for (LogSegment segment : segments) { boolean deleted = false; try { try { segment.getMessageSet().close(); } catch (IOException e) { ...
java
public void startup() { if (config.getEnableZookeeper()) { serverRegister.registerBrokerInZk(); for (String topic : getAllTopics()) { serverRegister.processTask(new TopicTask(TopicTask.TaskType.CREATE, topic)); } startupLatch.countDown(); }...
java
public void flushAllLogs(final boolean force) { Iterator<Log> iter = getLogIterator(); while (iter.hasNext()) { Log log = iter.next(); try { boolean needFlush = force; if (!needFlush) { long timeSinceLastFlush = System.currentTi...
java
public ILog getLog(String topic, int partition) { TopicNameValidator.validate(topic); Pool<Integer, Log> p = getLogPool(topic, partition); return p == null ? null : p.get(partition); }
java
public ILog getOrCreateLog(String topic, int partition) throws IOException { final int configPartitionNumber = getPartition(topic); if (partition >= configPartitionNumber) { throw new IOException("partition is bigger than the number of configuration: " + configPartitionNumber); } ...
java
public int createLogs(String topic, final int partitions, final boolean forceEnlarge) { TopicNameValidator.validate(topic); synchronized (logCreationLock) { final int configPartitions = getPartition(topic); if (configPartitions >= partitions || !forceEnlarge) { re...
java
public List<Long> getOffsets(OffsetRequest offsetRequest) { ILog log = getLog(offsetRequest.topic, offsetRequest.partition); if (log != null) { return log.getOffsetsBefore(offsetRequest); } return ILog.EMPTY_OFFSETS; }
java
private Send handle(SelectionKey key, Receive request) { final short requestTypeId = request.buffer().getShort(); final RequestKeys requestType = RequestKeys.valueOf(requestTypeId); if (requestLogger.isTraceEnabled()) { if (requestType == null) { throw new InvalidRequ...
java
public static Authentication build(String crypt) throws IllegalArgumentException { if(crypt == null) { return new PlainAuth(null); } String[] value = crypt.split(":"); if(value.length == 2 ) { String type = value[0].trim(); String password = v...
java
public static Broker createBroker(int id, String brokerInfoString) { String[] brokerInfo = brokerInfoString.split(":"); String creator = brokerInfo[0].replace('#', ':'); String hostname = brokerInfo[1].replace('#', ':'); String port = brokerInfo[2]; boolean autocreated = Boolean....
java
public static StringConsumers buildConsumer( final String zookeeperConfig,// final String topic,// final String groupId, // final IMessageListener<String> listener) { return buildConsumer(zookeeperConfig, topic, groupId, listener, 2); }
java
public MessageSet read(long readOffset, long size) throws IOException { return new FileMessageSet(channel, this.offset + readOffset, // Math.min(this.offset + readOffset + size, highWaterMark()), false, new AtomicBoolean(false)); }
java
public long[] append(MessageSet messages) throws IOException { checkMutable(); long written = 0L; while (written < messages.getSizeInBytes()) written += messages.writeTo(channel, 0, messages.getSizeInBytes()); long beforeOffset = setSize.getAndAdd(written); return new...
java
public void flush() throws IOException { checkMutable(); long startTime = System.currentTimeMillis(); channel.force(true); long elapsedTime = System.currentTimeMillis() - startTime; LogFlushStats.recordFlushRequest(elapsedTime); logger.debug("flush time " + elapsedTime); ...
java
private long recover() throws IOException { checkMutable(); long len = channel.size(); ByteBuffer buffer = ByteBuffer.allocate(4); long validUpTo = 0; long next = 0L; do { next = validateMessage(channel, validUpTo, len, buffer); if (next >= 0) vali...
java
private long validateMessage(FileChannel channel, long start, long len, ByteBuffer buffer) throws IOException { buffer.rewind(); int read = channel.read(buffer, start); if (read < 4) return -1; // check that we have sufficient bytes left in the file int size = buffer.getInt(0); ...
java
public int createPartitions(String topic, int partitionNum, boolean enlarge) throws IOException { KV<Receive, ErrorMapping> response = send(new CreaterRequest(topic, partitionNum, enlarge)); return Utils.deserializeIntArray(response.k.buffer())[0]; }
java
public int deleteTopic(String topic, String password) throws IOException { KV<Receive, ErrorMapping> response = send(new DeleterRequest(topic, password)); return Utils.deserializeIntArray(response.k.buffer())[0]; }
java
public ByteBuffer payload() { ByteBuffer payload = buffer.duplicate(); payload.position(headerSize(magic())); payload = payload.slice(); payload.limit(payloadSize()); payload.rewind(); return payload; }
java
private void validateSegments(List<LogSegment> segments) { synchronized (lock) { for (int i = 0; i < segments.size() - 1; i++) { LogSegment curr = segments.get(i); LogSegment next = segments.get(i + 1); if (curr.start() + curr.size() != next.start()) {...
java
public MessageSet read(long offset, int length) throws IOException { List<LogSegment> views = segments.getView(); LogSegment found = findRange(views, offset, views.size()); if (found == null) { if (logger.isTraceEnabled()) { logger.trace(format("NOT FOUND MessageSet f...
java
public void flush() throws IOException { if (unflushed.get() == 0) return; synchronized (lock) { if (logger.isTraceEnabled()) { logger.debug("Flushing log '" + name + "' last flushed: " + getLastFlushedTime() + " current time: " + System .currentTimeM...
java
public static <T extends Range> T findRange(List<T> ranges, long value, int arraySize) { if (ranges.size() < 1) return null; T first = ranges.get(0); T last = ranges.get(arraySize - 1); // check out of bounds if (value < first.start() || value > last.start() + last.size()) { ...
java
public static String nameFromOffset(long offset) { NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumIntegerDigits(20); nf.setMaximumFractionDigits(0); nf.setGroupingUsed(false); return nf.format(offset) + Log.FileSuffix; }
java
List<LogSegment> markDeletedWhile(LogSegmentFilter filter) throws IOException { synchronized (lock) { List<LogSegment> view = segments.getView(); List<LogSegment> deletable = new ArrayList<LogSegment>(); for (LogSegment seg : view) { if (filter.filter(seg)) { ...
java
public void verifyMessageSize(int maxMessageSize) { Iterator<MessageAndOffset> shallowIter = internalIterator(true); while(shallowIter.hasNext()) { MessageAndOffset messageAndOffset = shallowIter.next(); int payloadSize = messageAndOffset.message.payloadSize(); if(payload...
java
public void close() { Closer.closeQuietly(acceptor); for (Processor processor : processors) { Closer.closeQuietly(processor); } }
java
public void startup() throws InterruptedException { final int maxCacheConnectionPerThread = serverConfig.getMaxConnections() / processors.length; logger.debug("start {} Processor threads",processors.length); for (int i = 0; i < processors.length; i++) { processors[i] = new Processor(...
java
public static List<String> getChildrenParentMayNotExist(ZkClient zkClient, String path) { try { return zkClient.getChildren(path); } catch (ZkNoNodeException e) { return null; } }
java
public static Cluster getCluster(ZkClient zkClient) { Cluster cluster = new Cluster(); List<String> nodes = getChildrenParentMayNotExist(zkClient, BrokerIdsPath); for (String node : nodes) { final String brokerInfoString = readData(zkClient, BrokerIdsPath + "/" + node); c...
java
public static Map<String, List<String>> getPartitionsForTopics(ZkClient zkClient, Collection<String> topics) { Map<String, List<String>> ret = new HashMap<String, List<String>>(); for (String topic : topics) { List<String> partList = new ArrayList<String>(); List<String> brokers ...
java
public static Map<String, List<String>> getConsumersPerTopic(ZkClient zkClient, String group) { ZkGroupDirs dirs = new ZkGroupDirs(group); List<String> consumers = getChildrenParentMayNotExist(zkClient, dirs.consumerRegistryDir); // Map<String, List<String>> consumersPerTopicMap = new Ha...
java
public static void createEphemeralPath(ZkClient zkClient, String path, String data) { try { zkClient.createEphemeral(path, Utils.getBytes(data)); } catch (ZkNoNodeException e) { createParentPath(zkClient, path); zkClient.createEphemeral(path, Utils.getBytes(data)); ...
java
public void addProducer(Broker broker) { Properties props = new Properties(); props.put("host", broker.host); props.put("port", "" + broker.port); props.putAll(config.getProperties()); if (sync) { SyncProducer producer = new SyncProducer(new SyncProducerConfig(props))...
java
public void send(ProducerPoolData<V> ppd) { if (logger.isDebugEnabled()) { logger.debug("send message: " + ppd); } if (sync) { Message[] messages = new Message[ppd.data.size()]; int index = 0; for (V v : ppd.data) { messages[index] ...
java
public void close() { logger.info("Closing all sync producers"); if (sync) { for (SyncProducer p : syncProducers.values()) { p.close(); } } else { for (AsyncProducer<V> p : asyncProducers.values()) { p.close(); } ...
java
public ProducerPoolData<V> getProducerPoolData(String topic, Partition bidPid, List<V> data) { return new ProducerPoolData<V>(topic, bidPid, data); }
java
public static ProducerRequest readFrom(ByteBuffer buffer) { String topic = Utils.readShortString(buffer); int partition = buffer.getInt(); int messageSetSize = buffer.getInt(); ByteBuffer messageSetBuffer = buffer.slice(); messageSetBuffer.limit(messageSetSize); buffer.po...
java
protected String getExpectedMessage() { StringBuilder syntax = new StringBuilder("<tag> "); syntax.append(getName()); String args = getArgSyntax(); if (args != null && args.length() > 0) { syntax.append(' '); syntax.append(args); } retu...
java
public ServerSetup createCopy(String bindAddress) { ServerSetup setup = new ServerSetup(getPort(), bindAddress, getProtocol()); setup.setServerStartupTimeout(getServerStartupTimeout()); setup.setConnectionTimeout(getConnectionTimeout()); setup.setReadTimeout(getReadTimeout()); ...
java
public static ServerSetup[] verbose(ServerSetup[] serverSetups) { ServerSetup[] copies = new ServerSetup[serverSetups.length]; for (int i = 0; i < serverSetups.length; i++) { copies[i] = serverSetups[i].createCopy().setVerbose(true); } return copies; }
java
public void doRun(Properties properties) { ServerSetup[] serverSetup = new PropertiesBasedServerSetupBuilder().build(properties); if (serverSetup.length == 0) { printUsage(System.out); } else { greenMail = new GreenMail(serverSetup); log.info("Starting Green...
java
private String decodeStr(String str) { try { return MimeUtility.decodeText(str); } catch (UnsupportedEncodingException e) { return str; } }
java
public static void copyStream(final InputStream src, OutputStream dest) throws IOException { byte[] buffer = new byte[1024]; int read; while ((read = src.read(buffer)) > -1) { dest.write(buffer, 0, read); } dest.flush(); }
java
public static int getLineCount(String str) { if (null == str || str.isEmpty()) { return 0; } int count = 1; for (char c : str.toCharArray()) { if ('\n' == c) { count++; } } return count; }
java
public static void sendTextEmail(String to, String from, String subject, String msg, final ServerSetup setup) { sendMimeMessage(createTextEmail(to, from, subject, msg, setup)); }
java
public static void sendMimeMessage(MimeMessage mimeMessage) { try { Transport.send(mimeMessage); } catch (MessagingException e) { throw new IllegalStateException("Can not send message " + mimeMessage, e); } }
java
public static void sendMessageBody(String to, String from, String subject, Object body, String contentType, ServerSetup serverSetup) { try { Session smtpSession = getSession(serverSetup); MimeMessage mimeMessage = new MimeMessage(smtpSession); mimeMessage.setRecipients(...
java
public static MimeMultipart createMultipartWithAttachment(String msg, final byte[] attachment, final String contentType, final String filename, String description) { try { MimeMultipart multiPart = new MimeMultipart(); ...
java
public static Session getSession(final ServerSetup setup, Properties mailProps) { Properties props = setup.configureJavaMailSessionProperties(mailProps, false); log.debug("Mail session properties are {}", props); return Session.getInstance(props, null); }
java
public static void setQuota(final GreenMailUser user, final Quota quota) { Session session = GreenMailUtil.getSession(ServerSetupTest.IMAP); try { Store store = session.getStore("imap"); store.connect(user.getEmail(), user.getPassword()); try { (...
java
public boolean hasUser(String userId) { String normalized = normalizerUserName(userId); return loginToUser.containsKey(normalized) || emailToUser.containsKey(normalized); }
java
protected void closeServerSocket() { // Close server socket, we do not accept new requests anymore. // This also terminates the server thread if blocking on socket.accept. if (null != serverSocket) { try { if (!serverSocket.isClosed()) { serverSock...
java
protected synchronized void quit() { log.debug("Stopping {}", getName()); closeServerSocket(); // Close all handlers. Handler threads terminate if run loop exits synchronized (handlers) { for (ProtocolHandler handler : handlers) { handler.close(); ...
java
@Override public final synchronized void stopService(long millis) { running = false; try { if (keepRunning) { keepRunning = false; interrupt(); quit(); if (0L == millis) { join(); } else {...
java
private static Date getSentDate(MimeMessage msg, Date defaultVal) { if (msg == null) { return defaultVal; } try { Date sentDate = msg.getSentDate(); if (sentDate == null) { return defaultVal; } else { return...
java
private String parseEnvelope() { List<String> response = new ArrayList<>(); //1. Date --------------- response.add(LB + Q + sentDateEnvelopeString + Q + SP); //2. Subject --------------- if (subject != null && (subject.length() != 0)) { response.add(Q + escapeHe...
java
private String parseAddress(String address) { try { StringBuilder buf = new StringBuilder(); InternetAddress[] netAddrs = InternetAddress.parseHeader(address, false); for (InternetAddress netAddr : netAddrs) { if (buf.length() > 0) { ...
java
void decodeContentType(String rawLine) { int slash = rawLine.indexOf('/'); if (slash == -1) { // if (DEBUG) getLogger().debug("decoding ... no slash found"); return; } else { primaryType = rawLine.substring(0, slash).trim(); } int semico...
java
protected void doConfigure() { if (config != null) { for (UserBean user : config.getUsersToCreate()) { setUser(user.getEmail(), user.getLogin(), user.getPassword()); } getManagers().getUserManager().setAuthRequired(!config.isAuthenticationDisabled()); ...
java
public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) { return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush); }
java
protected Map<String, AbstractServer> createServices(ServerSetup[] config, Managers mgr) { Map<String, AbstractServer> srvc = new HashMap<>(); for (ServerSetup setup : config) { if (srvc.containsKey(setup.getProtocol())) { throw new IllegalArgumentException("Server '" + s...
java
public void okResponse(String responseCode, String message) { untagged(); message(OK); responseCode(responseCode); message(message); end(); }
java
@Override public void close() { // Use monitor to avoid race between external close and handler thread run() synchronized (closeMonitor) { // Close and clear streams, sockets etc. if (socket != null) { try { // Terminates thread bloc...
java
public static InputStream toStream(String content, Charset charset) { byte[] bytes = content.getBytes(charset); return new ByteArrayInputStream(bytes); }
java
public GreenMailConfiguration build(Properties properties) { GreenMailConfiguration configuration = new GreenMailConfiguration(); String usersParam = properties.getProperty(GREENMAIL_USERS); if (null != usersParam) { String[] usersArray = usersParam.split(","); for (Strin...
java
private ServerSetup[] createServerSetup() { List<ServerSetup> setups = new ArrayList<>(); if (smtpProtocol) { smtpServerSetup = createTestServerSetup(ServerSetup.SMTP); setups.add(smtpServerSetup); } if (smtpsProtocol) { smtpsServerSetup = createTestSe...
java
public String tag(ImapRequestLineReader request) throws ProtocolException { CharacterValidator validator = new TagCharValidator(); return consumeWord(request, validator); }
java
public String astring(ImapRequestLineReader request) throws ProtocolException { char next = request.nextWordChar(); switch (next) { case '"': return consumeQuoted(request); case '{': return consumeLiteral(request); default: ...
java
public String nstring(ImapRequestLineReader request) throws ProtocolException { char next = request.nextWordChar(); switch (next) { case '"': return consumeQuoted(request); case '{': return consumeLiteral(request); default: ...
java