text:
package com.magnet.mmx.server.plugin.mmxmgmt.handler;

import com.magnet.mmx.protocol.*;
import com.magnet.mmx.server.common.data.AppEntity;
import com.magnet.mmx.server.plugin.mmxmgmt.db.*;
import com.magnet.mmx.server.plugin.mmxmgmt.event.MMXMaxDevicesPerAppLimitReachedEvent;
import com.magnet.mmx.server.plugin.mmxmgmt.util.*;
import com.magnet.mmx.util.GsonData;
import com.magnet.mmx.util.Utils;
import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Handler that handles the requests for managing devices
 */
public class DeviceHandler extends IQHandler {
  private static Logger LOGGER = LoggerFactory.getLogger(DeviceHandler.class);
  private static final String COMMAND_KEY = com.magnet.mmx.protocol.Constants.MMX_ATTR_COMMAND;
  /**
   * Constructor that takes the module name
   * @param moduleName
   */
  public DeviceHandler(String moduleName) {
    super(moduleName);
  }

  @Override
  public IQ handleIQ(IQ iq) throws UnauthorizedException {
    LOGGER.info("handleIQ is called");
    AppDAO dao = new AppDAOImpl(new OpenFireDBConnectionProvider());
    JID fromJID = iq.getFrom();
    String appId = JIDUtil.getAppId(fromJID);

    AppEntity appEntity = dao.getAppForAppKey(appId);
    if (appEntity == null) {
      return IQUtils.createErrorIQ(iq,
          DeviceOperationStatusCode.INVALID_APP_ID.getMessage(),
          DeviceOperationStatusCode.INVALID_APP_ID.getCode());
    }
    /*
      retrieve the command that we are processing
     */
    Element element = iq.getChildElement();
    String payload = element.getText();
    String command = element.attributeValue(COMMAND_KEY);
    if (command == null || command.isEmpty() || command.trim().isEmpty()) {
      return IQUtils.createErrorIQ(iq,
          DeviceOperationStatusCode.INVALID_COMMAND_VALUE.getMessage(),
          DeviceOperationStatusCode.INVALID_COMMAND_VALUE.getCode());
    }

    Constants.DeviceCommand deviceCommand = null;
    try {
      deviceCommand = Constants.DeviceCommand.valueOf(command.toUpperCase());
    } catch (IllegalArgumentException e) {
      LOGGER.info("Invalid device command string:" + command, e);
    }
    if (deviceCommand == null) {
      return IQUtils.createErrorIQ(iq,
          DeviceOperationStatusCode.INVALID_COMMAND_VALUE.getMessage(),
          DeviceOperationStatusCode.INVALID_COMMAND_VALUE.getCode());
    }

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Processing command:" + deviceCommand.toString());
    }

    switch (deviceCommand) {
    case REGISTER:
      return processRegistration(iq, fromJID, appEntity, payload);
    case UNREGISTER:
      return processDeRegistration(iq, fromJID, appEntity, payload);
    case QUERY:
      return processQuery(iq, fromJID, appEntity, payload);
    case GETTAGS:
      return processGetTags(iq, fromJID, appEntity, payload);
    case SETTAGS:
      return processSetTags(iq, fromJID, appEntity, payload);
    case ADDTAGS:
      return processAddTags(iq, fromJID, appEntity, payload);
    case REMOVETAGS:
      return processRemoveTags(iq, fromJID, appEntity, payload);
    }
    return null;
  }

  @Override
  public IQHandlerInfo getInfo() {
    return new IQHandlerInfo(Constants.MMX, Constants.MMX_NS_DEV);
  }

  // Process device registration
  private IQ processRegistration(IQ input,JID fromJID, AppEntity appEntity, String payload) {
    DeviceDAO deviceDAO = new DeviceDAOImpl(new OpenFireDBConnectionProvider());
    String appId = appEntity.getAppId();
    String userId = JIDUtil.getUserId(fromJID);

    DevReg deviceRequest = DevReg.fromJson(payload);

    IQ error = validateRequest(input, deviceRequest);
    if (error != null) {
      //validation failed
      return error;
    }

    DeviceEntity deviceEntity = deviceDAO.getDevice(deviceRequest.getDevId(), Helper.enumerateOSType(deviceRequest.getOsType()), appId);
    if (deviceEntity != null) {
      //this is an update
      String oldToken = deviceEntity.getClientToken();
      String newToken = deviceRequest.getPushToken();
      boolean changed = false;
      if (oldToken == null && newToken == null) {
        changed = false;
      } else if (oldToken == null && newToken != null) {
        changed = true;
      } else if (oldToken != null && newToken == null) {
        changed = true;
      } else if (!oldToken.equals(newToken)) {
        changed = true;
      }
      int rowCount = deviceDAO.updateDevice(deviceRequest.getDevId(), Helper.enumerateOSType(deviceRequest.getOsType()), appId, deviceRequest, userId, DeviceStatus.ACTIVE);

      if (changed) {
        PushStatus status = null;
        if (newToken != null) {
          status = PushStatus.VALID;
        }
        LOGGER.trace("processRegistration : updateDevice resultCount={}, deviceId={}", rowCount, deviceRequest.getDevId());
        deviceDAO.updatePushStatus(deviceRequest.getDevId(), Helper.enumerateOSType(deviceRequest.getOsType()), appId, status);
      }
    } else {
      int id =  deviceDAO.addDevice(userId, appId, deviceRequest);
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format("Device created with id:%d using request:%s for app id: %s", id, deviceRequest.toString(), appId));
      }
    }

    MMXStatus devResp = new MMXStatus()
      .setCode(DeviceOperationStatusCode.DEVICE_REGISTERED.getCode())
      .setMessage(DeviceOperationStatusCode.DEVICE_REGISTERED.getMessage());
    return IQUtils.createResultIQ(input, devResp.toJson());
  }

  private IQ processDeRegistration(IQ input,JID fromJID, AppEntity appEntity, String payload) {
    DeviceDAO deviceDAO = new DeviceDAOImpl(new OpenFireDBConnectionProvider());
    int appId = appEntity.getId();
    DevId rqt = DevId.fromJson(payload);

    IQ error = validateRequest(input, rqt);
    if (error != null) {
      //validation failed
      return error;
    }
    int id = deviceDAO.deactivateDevice(rqt.getDevId());
    MMXStatus devResp = new MMXStatus()
      .setCode(DeviceOperationStatusCode.DEVICE_UNREGISTERED.getCode());
    return IQUtils.createResultIQ(input, devResp.toJson());
  }

  private DeviceInfo convert(DeviceEntity entity) {
    DeviceInfo devInfo = new DeviceInfo()
              .setCarrierInfo(entity.getCarrierInfo())
              .setDevId(entity.getDeviceId())
              .setDisplayName(entity.getName())
              .setModelInfo(null)
              .setOsType(entity.getOsType() == null ?
                  null : entity.getOsType().toString())
              .setOsVersion(entity.getOsVersion())
              .setPhoneNumber(entity.getPhoneNumber())
              .setExtras(null)
              .setPushType(entity.getTokenType() == null ?
                  null : entity.getTokenType().toString())
              .setPushToken(entity.getClientToken())
              .setTags(null);
    return devInfo;
  }

  // Process the query for device ID's owned by a user using user ID.
  private IQ processQuery(IQ input, JID fromJID, AppEntity appEntity, String payload) {
    DeviceDAO deviceDAO = new DeviceDAOImpl(new OpenFireDBConnectionProvider());
    String appId = appEntity.getAppId();
    String userId = GsonData.getGson().fromJson(payload, String.class);

    if (userId == null) {
      userId = JIDUtil.getUserId(fromJID);
    }
    IQ error = validateRequest(input, userId);
    if (error != null) {
      return error;
    }
    List<DeviceEntity> list = deviceDAO.getDevices(appId, userId, DeviceStatus.ACTIVE);
    DevList devList = new DevList(list.size());
    for (DeviceEntity entity : list) {
      devList.add(convert(entity));
    }
    return IQUtils.createResultIQ(input, GsonData.getGson().toJson(devList));
  }

  private IQ validateRequest(IQ input, DevReg deviceRequest) {
    String apiKey = deviceRequest.getApiKey();
    AppDAO appDAO = new AppDAOImpl(new OpenFireDBConnectionProvider());
    AppEntity app = appDAO.getAppUsingAPIKey(apiKey);

    String ownerJid = JIDUtil.getUserId(input.getFrom());
    if (app == null) {
      return IQUtils.createErrorIQ(input,
          DeviceOperationStatusCode.INVALID_API_KEY.getMessage(),
          DeviceOperationStatusCode.INVALID_API_KEY.getCode());
    }
    String deviceId = deviceRequest.getDevId();
    if (deviceId == null || deviceId.isEmpty()) {
      return IQUtils.createErrorIQ(input,
          DeviceOperationStatusCode.INVALID_DEVICE_ID.getMessage(),
          DeviceOperationStatusCode.INVALID_DEVICE_ID.getCode());

    }
    String osTypeString = deviceRequest.getOsType();
    OSType osType = Helper.enumerateOSType(osTypeString);
    if (osType == null) {
      return IQUtils.createErrorIQ(input,
          DeviceOperationStatusCode.INVALID_OS_TYPE.getMessage(),
          DeviceOperationStatusCode.INVALID_OS_TYPE.getCode());
    }

    String pushTypeString = deviceRequest.getPushType();
    if (pushTypeString != null) {
      PushType pushType = Helper.enumeratePushType(pushTypeString);
      if (pushType == null) {
        return IQUtils.createErrorIQ(input,
            DeviceOperationStatusCode.INVALID_PUSH_TYPE.getMessage(),
            DeviceOperationStatusCode.INVALID_PUSH_TYPE.getCode());
      }
    }

    //validate phone number
    String phoneNumber = deviceRequest.getPhoneNumber();
    if (phoneNumber != null) {
      boolean valid = Helper.checkPhoneNumber(phoneNumber);
      if (!valid) {
        return IQUtils.createErrorIQ(input,
            DeviceOperationStatusCode.INVALID_PHONE_NUMBER.getMessage(),
            DeviceOperationStatusCode.INVALID_PHONE_NUMBER.getCode());
      }
    }

    //validate the carrier information
    String carrierInfo = deviceRequest.getCarrierInfo();
    if (carrierInfo != null) {
      CarrierEnum carrierEnum = Helper.enumerateCarrierInfo(carrierInfo);
      if (carrierEnum == null) {
        return IQUtils.createErrorIQ(input,
            DeviceOperationStatusCode.INVALID_CARRIER.getMessage(),
            DeviceOperationStatusCode.INVALID_CARRIER.getCode());
      }
    }
    String appId = app.getAppId();
    if(AlertsUtil.maxDevicesPerAppLimitReached(appId, ownerJid)) {
      DeviceOperationStatusCode code = DeviceOperationStatusCode.DEVICES_PER_APP_EXCEEDED;
      code.setMessage("Reached devices per app limit : " + MMXConfiguration.getConfiguration().getLong(MMXConfigKeys.MAX_DEVICES_PER_APP, -1));
      int limit = AlertsUtil.getMaxDevicePerAppLimit();
      AlertEventsManager.post(new MMXMaxDevicesPerAppLimitReachedEvent(appId, limit));
      return IQUtils.createErrorIQ(input, code.getMessage(), code.getCode());
    }

    return null;
  }

  private IQ processGetTags(IQ iq, JID fromJID, AppEntity appEntity, String payload) {
    DeviceDAO deviceDAO = new DeviceDAOImpl(new OpenFireDBConnectionProvider());
    String appId = appEntity.getAppId();
    String userId = JIDUtil.getUserId(fromJID);
    DevId rqt = GsonData.getGson().fromJson(payload, DevId.class);

    DeviceEntity devEntity = deviceDAO.getDeviceUsingId(appId, rqt.getDevId(),
        DeviceStatus.ACTIVE);
    if (devEntity == null) {
      return IQUtils.createErrorIQ(iq, "Device ID not found", StatusCode.NOT_FOUND);
    }
    if (!userId.equals(devEntity.getOwnerId())) {
      return IQUtils.createErrorIQ(iq, "Not a device owner", StatusCode.FORBIDDEN);
    }

    List<TagEntity> tagEntities = DBUtil.getTagDAO().getTagEntitiesForDevice(devEntity);
    List<String> tags = new ArrayList<String>();
    List<Date> dates = new ArrayList<Date>();
    for(TagEntity tagEntity : tagEntities) {
      tags.add(tagEntity.getTagname());
      dates.add(tagEntity.getCreationDate());
    }

    Collections.sort(dates, Collections.reverseOrder());

    DevTags devTags = new DevTags(rqt.getDevId(), tags,
        Utils.isNullOrEmpty(dates) ? null : dates.get(0));
    return IQUtils.createResultIQ(iq, devTags.toJson());
  }

  private IQ processSetTags(IQ iq, JID fromJID, AppEntity appEntity, String payload) {
    String appId = appEntity.getAppId();
    String userId = JIDUtil.getUserId(fromJID);
    DevTags rqt = DevTags.fromJson(payload);
    DeviceDAO deviceDAO = new DeviceDAOImpl(new OpenFireDBConnectionProvider());

    DeviceEntity devEntity = deviceDAO.getDeviceUsingId(appId, rqt.getDevId(),
            DeviceStatus.ACTIVE);
    if (devEntity == null) {
      return IQUtils.createErrorIQ(iq, "Device not found", StatusCode.NOT_FOUND);
    }

    if (!userId.equals(devEntity.getOwnerId())) {
      return IQUtils.createErrorIQ(iq, "Not a device owner", StatusCode.FORBIDDEN);
    }

    TagDAO tagDAO = DBUtil.getTagDAO();
    tagDAO.deleteAllTagsForDevice(devEntity);

    List<String> tagNames = rqt.getTags();

    if (!Utils.isNullOrEmpty(tagNames)) {
      for(String tag : tagNames) {
        try {
          tagDAO.createDeviceTag(tag, appId, devEntity.getId());
        } catch (DbInteractionException e) {
          LOGGER.error("processSetTags : unable to set tags for device={}", devEntity);
          return IQUtils.createErrorIQ(iq, "server error in creating tags", StatusCode.INTERNAL_ERROR);
        }
      }
    }

    MMXStatus status = new MMXStatus().setCode(StatusCode.SUCCESS).setMessage("successfully set tags");
    return IQUtils.createResultIQ(iq, status.toJson());
  }

  private IQ processAddTags(IQ iq, JID fromJID, AppEntity appEntity, String payload) {
    String appId = appEntity.getAppId();
    String userId = JIDUtil.getUserId(fromJID);
    DevTags rqt = DevTags.fromJson(payload);
    DeviceDAO deviceDAO = new DeviceDAOImpl(new OpenFireDBConnectionProvider());

    DeviceEntity devEntity = deviceDAO.getDeviceUsingId(appId, rqt.getDevId(),
        DeviceStatus.ACTIVE);
    if (devEntity == null) {
      return IQUtils.createErrorIQ(iq, "Device not found", StatusCode.NOT_FOUND);
    }
    if (!userId.equals(devEntity.getOwnerId())) {
      return IQUtils.createErrorIQ(iq, "Not a device owner", StatusCode.FORBIDDEN);
    }

    // Add the tags
    for(String tag : rqt.getTags()) {
      try {
        DBUtil.getTagDAO().createDeviceTag(tag, devEntity.getAppId(), devEntity.getId());
      } catch (IllegalArgumentException e) {
        return IQUtils.createErrorIQ(iq, e.getMessage(), StatusCode.BAD_REQUEST);
      } catch (Exception e) {
        return IQUtils.createErrorIQ(iq, "Device does not exist", StatusCode.FORBIDDEN);
      }
    }

    MMXStatus status = new MMXStatus().setCode(StatusCode.SUCCESS).setMessage("successfully added tags");
    return IQUtils.createResultIQ(iq, status.toJson());
  }

  private IQ processRemoveTags(IQ iq, JID fromJID, AppEntity appEntity, String payload) {
    String appId = appEntity.getAppId();
    String userId = JIDUtil.getUserId(fromJID);
    DevTags rqt = DevTags.fromJson(payload);
    DeviceDAO deviceDAO = new DeviceDAOImpl(new OpenFireDBConnectionProvider());

    DeviceEntity devEntity = deviceDAO.getDeviceUsingId(appId, rqt.getDevId(),
        DeviceStatus.ACTIVE);
    if (devEntity == null) {
      return IQUtils.createErrorIQ(iq, "Device not found", StatusCode.NOT_FOUND);
    }
    if (!userId.equals(devEntity.getOwnerId())) {
      return IQUtils.createErrorIQ(iq, "Not a device owner", StatusCode.FORBIDDEN);
    }

    TagDAO tagDAO = DBUtil.getTagDAO();
    if(!Utils.isNullOrEmpty(rqt.getTags()))
      tagDAO.deleteTagsForDevice(devEntity, rqt.getTags());

    MMXStatus status = new MMXStatus().setCode(StatusCode.SUCCESS).setMessage("successfully removed tags");
    return IQUtils.createResultIQ(iq, status.toJson());
  }

  /**
   * Validate the un reg request.
   * @param input
   * @param deviceRequest
   * @return a non null IQ if the validation fails
   */
  private IQ validateRequest(IQ input, DevId deviceRequest) {
    String deviceId = deviceRequest.getDevId();
    if (deviceId == null || deviceId.isEmpty()) {
      return IQUtils.createErrorIQ(input,
          DeviceOperationStatusCode.INVALID_DEVICE_ID.getMessage(),
          DeviceOperationStatusCode.INVALID_DEVICE_ID.getCode());
    }
    return null;
  }

  private IQ validateRequest(IQ input, String userId) {
    if (userId == null || userId.isEmpty()) {
      return IQUtils.createErrorIQ(input,
          DeviceOperationStatusCode.INVALID_USER_ID.getMessage(),
          DeviceOperationStatusCode.INVALID_USER_ID.getCode());
    }
    return null;
  }
  /**
   * Enum for the status codes
   */
  public static enum DeviceOperationStatusCode {
    DEVICE_REGISTERED(201, "Device registered"),
    DEVICE_UNREGISTERED(200, "Device unregistered"),
    INVALID_APP_ID (400, "Invalid app ID"),
    INVALID_API_KEY(400, "Invalid api key"),
    INVALID_USER_ID(400, "Invalid user ID"),
    INVALID_DEVICE_ID (400, "Invalid deviceId"),
    INVALID_OS_TYPE (400, "Invalid osType"),
    INVALID_PUSH_TYPE (400, "Invalid pushType"),
    INVALID_COMMAND_VALUE (400, "Invalid command value"),
    INVALID_PHONE_NUMBER (400, "Invalid phone number"),
    INVALID_CARRIER (400, "Invalid carrier"),
    INVALID_OWNER_ID(400, "Invalid Owner ID"),
    DEVICES_PER_APP_EXCEEDED(400, ""),
    DEVICES_PER_USER_EXCEEDED(400, "");

    private int code;
    private String message;
    DeviceOperationStatusCode(int c, String m) {
      code = c;
      message = m;
    }

    public int getCode() {
      return code;
    }

    public String getMessage() {
      return message;
    }

    public void setMessage(String message) {
      this.message = message;
    }
  }
}


text:
package org.spockframework.runtime.extension.builtin;

import org.spockframework.runtime.SpockTimeoutError;
import org.spockframework.runtime.extension.*;
import org.spockframework.util.TimeUtil;
import spock.lang.Timeout;

import java.util.concurrent.*;

/**
 * Times out a method invocation if it takes too long. The method invocation
 * will occur on the regular test framework thread. This can be important
 * for integration tests with thread-local state.
 *
 * @author Peter Niederwieser
 */

public class TimeoutInterceptor implements IMethodInterceptor {
  private final Timeout timeout;

  public TimeoutInterceptor(Timeout timeout) {
    this.timeout = timeout;
  }

  @Override
  public void intercept(final IMethodInvocation invocation) throws Throwable {
    final Thread mainThread = Thread.currentThread();
    final SynchronousQueue<StackTraceElement[]> sync = new SynchronousQueue<>();
    final CountDownLatch startLatch = new CountDownLatch(2);

    new Thread(String.format("[spock.lang.Timeout] Watcher for method '%s'", invocation.getMethod().getName())) {
      @Override
      public void run() {
        StackTraceElement[] stackTrace = new StackTraceElement[0];
        long waitMillis = timeout.unit().toMillis(timeout.value());
        boolean synced = false;

        try {
          startLatch.countDown();
          startLatch.await(5, TimeUnit.SECONDS);
        } catch (InterruptedException ignored) {
          System.out.printf("[spock.lang.Timeout] Could not sync with Feature for method '%s'", invocation.getMethod().getName());
        }

        while (!synced) {
          try {
            synced = sync.offer(stackTrace, waitMillis, TimeUnit.MILLISECONDS);
          } catch (InterruptedException ignored) {
            // The mission of this thread is to repeatedly interrupt the main thread until
            // the latter returns. Once this mission has been accomplished, this thread will die quickly
          }
          if (!synced) {
            if (stackTrace.length == 0) {
              stackTrace = mainThread.getStackTrace();
              waitMillis = 250;
            } else {
              waitMillis *= 2;
              System.out.printf("[spock.lang.Timeout] Method '%s' has not yet returned - interrupting. Next try in %1.2f seconds.\n",
                  invocation.getMethod().getName(), waitMillis / 1000.);
            }
            mainThread.interrupt();
          }
        }
      }
    }.start();

    try {
      startLatch.countDown();
      startLatch.await(5, TimeUnit.SECONDS);
    } catch (InterruptedException ignored) {
      System.out.printf("[spock.lang.Timeout] Could not sync with Watcher for method '%s'", invocation.getMethod().getName());
    }

    Throwable saved = null;
    try {
      invocation.proceed();
    } catch (Throwable t) {
      saved = t;
    }
    StackTraceElement[] stackTrace = null;
    while (stackTrace == null) {
      try {
        stackTrace = sync.take();
      } catch (InterruptedException e) {
        // There is a small chance that this came from the watcher thread,
        // i.e. the two threads narrowly missed each other at the sync point.
        // Therefore, let's sync again to learn whether this thread has timed out or not.
        // As this won't take long, it should also be acceptable if this thread
        // got interrupted by some other thread. To report on the latter case,
        // we save off the exception, overriding any previously saved exception.
        saved = e;
      }
    }
    if (stackTrace.length > 0) {
      // We know that this thread got timed out (and interrupted) by the watcher thread and
      // act accordingly. We gloss over the fact that some other thread might also have tried to
      // interrupt this thread. This shouldn't be a problem in practice, in particular because
      // throwing an InterruptedException wouldn't abort the whole test run anyway.
      double timeoutSeconds = TimeUtil.toSeconds(timeout.value(), timeout.unit());
      String msg = String.format("Method timed out after %1.2f seconds", timeoutSeconds);
      SpockTimeoutError error = new SpockTimeoutError(timeoutSeconds, msg);
      error.setStackTrace(stackTrace);
      throw error;
    }
    if (saved != null) {
      throw saved;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package dev.tauri.seals.tests;

enum MyTestEnumWithToString {

	FOO,
	BAR;

	@Override
	public String toString() {
		switch (this) {
		case FOO: return "x";
		case BAR: return "y";
		default: throw new IllegalStateException();
		}
	}
}


text:
package org.cometd.server.websocket;

import java.io.IOException;
import java.net.ConnectException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.websocket.ClientEndpointConfig;
import javax.websocket.WebSocketContainer;
import org.cometd.bayeux.Channel;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.Promise;
import org.cometd.bayeux.client.ClientSession;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.LocalSession;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.client.BayeuxClient;
import org.cometd.client.ext.AckExtension;
import org.cometd.client.transport.ClientTransport;
import org.cometd.client.transport.TransportListener;
import org.cometd.client.websocket.jetty.JettyWebSocketTransport;
import org.cometd.client.websocket.okhttp.OkHttpWebSocketTransport;
import org.cometd.server.AbstractServerTransport;
import org.cometd.server.BayeuxServerImpl;
import org.cometd.server.ext.AcknowledgedMessagesExtension;
import org.cometd.server.http.JSONTransport;
import org.cometd.server.websocket.javax.WebSocketTransport;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import static org.cometd.bayeux.server.ConfigurableServerChannel.Initializer.Persistent;

public class BayeuxClientWebSocketTest extends ClientServerWebSocketTest {
    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testClientRetriesWebSocketTransportIfCannotConnect(String wsType) throws Exception {
        prepareAndStart(wsType, null);

        CountDownLatch connectLatch = new CountDownLatch(2);
        ClientTransport webSocketTransport = newWebSocketTransport(wsType, null);
        webSocketTransport.setOption(JettyWebSocketTransport.CONNECT_TIMEOUT_OPTION, 1000L);
        ClientTransport longPollingTransport = newLongPollingTransport(null);
        BayeuxClient client = new BayeuxClient(cometdURL, webSocketTransport, longPollingTransport) {
            @Override
            protected void sendConnect() {
                if ("websocket".equals(getTransport().getName())) {
                    connectLatch.countDown();
                }
                super.sendConnect();
            }
        };

        CountDownLatch failedLatch = new CountDownLatch(1);
        client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            if (!message.isSuccessful()) {
                failedLatch.countDown();
            }
        });

        int port = connector.getLocalPort();
        stopServer();

        client.handshake();
        Assertions.assertTrue(failedLatch.await(5, TimeUnit.SECONDS));

        prepareServer(wsType, port);
        startServer();

        Assertions.assertTrue(connectLatch.await(5, TimeUnit.SECONDS));

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testAbortThenRestart(String wsType) throws Exception {
        prepareAndStart(wsType, null);

        BayeuxClient client = newBayeuxClient(wsType);
        client.handshake();

        // Need to be sure that the second connect is sent otherwise
        // the abort and rehandshake may happen before the second
        // connect and the test will fail.
        Thread.sleep(1000);

        client.abort();
        Assertions.assertFalse(client.isConnected());

        // Restart
        CountDownLatch connectLatch = new CountDownLatch(1);
        client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            if (message.isSuccessful()) {
                connectLatch.countDown();
            }
        });
        client.handshake();
        Assertions.assertTrue(connectLatch.await(5, TimeUnit.SECONDS));
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));
        Assertions.assertTrue(client.isConnected());

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testRestart(String wsType) throws Exception {
        prepareAndStart(wsType, null);

        ClientTransport webSocketTransport = newWebSocketTransport(wsType, null);
        ClientTransport longPollingTransport = newLongPollingTransport(null);
        BayeuxClient client = new BayeuxClient(cometdURL, webSocketTransport, longPollingTransport);

        AtomicReference<CountDownLatch> connectedLatch = new AtomicReference<>(new CountDownLatch(1));
        AtomicReference<CountDownLatch> disconnectedLatch = new AtomicReference<>(new CountDownLatch(2));
        client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            if (message.isSuccessful() && "websocket".equals(client.getTransport().getName())) {
                connectedLatch.get().countDown();
            } else {
                disconnectedLatch.get().countDown();
            }
        });
        client.handshake();

        // Wait for connect
        Assertions.assertTrue(connectedLatch.get().await(10, TimeUnit.SECONDS));
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));
        Assertions.assertTrue(client.isConnected());
        Thread.sleep(1000);

        // Stop server
        int port = connector.getLocalPort();
        stopServer();
        Assertions.assertTrue(disconnectedLatch.get().await(10, TimeUnit.SECONDS));
        Assertions.assertFalse(client.isConnected());

        // restart server
        connectedLatch.set(new CountDownLatch(1));
        prepareServer(wsType, port);
        startServer();

        // Wait for connect
        Assertions.assertTrue(connectedLatch.get().await(10, TimeUnit.SECONDS));
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));
        Assertions.assertTrue(client.isConnected());

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testRestartAfterConnectWithFatalException(String wsType) throws Exception {
        prepareAndStart(wsType, null);

        // ConnectException is a recoverable exception that does not disable the transport.
        // Convert it to a fatal exception so the transport would be disabled.
        // However, since it connected before this fatal exception, the transport is not disabled.
        ClientTransport webSocketTransport;
        switch (wsType) {
            case WEBSOCKET_JSR356:
                webSocketTransport = new org.cometd.client.websocket.javax.WebSocketTransport(null, null, wsClientContainer) {
                    @Override
                    protected Delegate connect(WebSocketContainer container, ClientEndpointConfig configuration, String uri) throws IOException {
                        try {
                            return super.connect(container, configuration, uri);
                        } catch (ConnectException x) {
                            // Convert recoverable exception to unrecoverable.
                            throw new IOException(x);
                        }
                    }
                };
                break;
            case WEBSOCKET_JETTY:
                webSocketTransport = new JettyWebSocketTransport(null, null, wsClient) {
                    @Override
                    protected Delegate connect(WebSocketClient client, ClientUpgradeRequest request, String uri) throws IOException, InterruptedException {
                        try {
                            return super.connect(client, request, uri);
                        } catch (ConnectException x) {
                            // Convert recoverable exception to unrecoverable.
                            throw new IOException(x);
                        }
                    }
                };
                break;
            case WEBSOCKET_OKHTTP:
                webSocketTransport = new OkHttpWebSocketTransport(null, okHttpClient) {
                    @Override
                    protected Delegate connect(String uri, TransportListener listener, List<Message.Mutable> messages) {
                        return super.connect(uri, new TransportListener() {
                            @Override
                            public void onSending(List<? extends Message> messages) {
                                listener.onSending(messages);
                            }

                            @Override
                            public void onMessages(List<Message.Mutable> messages) {
                                listener.onMessages(messages);
                            }

                            @Override
                            public void onFailure(Throwable failure, List<? extends Message> messages) {
                                // Convert recoverable exception to unrecoverable.
                                listener.onFailure(new IOException(failure), messages);
                            }
                        }, messages);
                    }
                };
                break;
            default:
                throw new IllegalArgumentException();
        }

        BayeuxClient client = new BayeuxClient(cometdURL, webSocketTransport);

        AtomicReference<CountDownLatch> connectedLatch = new AtomicReference<>(new CountDownLatch(1));
        AtomicReference<CountDownLatch> disconnectedLatch = new AtomicReference<>(new CountDownLatch(2));
        client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            if (message.isSuccessful() && "websocket".equals(client.getTransport().getName())) {
                connectedLatch.get().countDown();
            } else {
                disconnectedLatch.get().countDown();
            }
        });
        client.handshake();

        // Wait for connect
        Assertions.assertTrue(connectedLatch.get().await(10, TimeUnit.SECONDS));
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));
        Assertions.assertTrue(client.isConnected());
        Thread.sleep(1000);

        // Stop server
        int port = connector.getLocalPort();
        server.stop();
        Assertions.assertTrue(disconnectedLatch.get().await(10, TimeUnit.SECONDS));
        Assertions.assertFalse(client.isConnected());

        // restart server
        connector.setPort(port);
        connectedLatch.set(new CountDownLatch(1));
        server.start();

        // Wait for connect
        Assertions.assertTrue(connectedLatch.get().await(10, TimeUnit.SECONDS));
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));
        Assertions.assertTrue(client.isConnected());

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testHandshakeExpiration(String wsType) throws Exception {
        prepareAndStart(wsType, null);

        long maxNetworkDelay = 2000;

        bayeux.getChannel(Channel.META_HANDSHAKE).addListener(new ServerChannel.MessageListener() {
            @Override
            public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message) {
                try {
                    Thread.sleep(maxNetworkDelay + maxNetworkDelay / 2);
                    return true;
                } catch (InterruptedException x) {
                    return false;
                }
            }
        });

        Map<String, Object> options = new HashMap<>();
        options.put(ClientTransport.MAX_NETWORK_DELAY_OPTION, maxNetworkDelay);
        ClientTransport webSocketTransport = newWebSocketTransport(wsType, options);
        BayeuxClient client = new BayeuxClient(cometdURL, webSocketTransport);
        long backOffIncrement = 1000;
        client.setBackOffStrategy(new BayeuxClient.BackOffStrategy.Linear(backOffIncrement, -1));

        // Expect 2 failed messages because the client backoffs and retries
        // This way we are sure that the late response from the first
        // expired handshake is not delivered to listeners
        CountDownLatch latch = new CountDownLatch(2);
        client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            Assertions.assertFalse(message.isSuccessful());
            if (!message.isSuccessful()) {
                latch.countDown();
            }
        });

        client.handshake();

        Assertions.assertTrue(latch.await(maxNetworkDelay * 2 + backOffIncrement * 2, TimeUnit.MILLISECONDS));

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testMetaConnectNotRespondedOnServerSidePublish(String wsType) throws Exception {
        prepareAndStart(wsType, null);

        BayeuxClient client = newBayeuxClient(wsType);

        String channelName = "/test";
        AtomicReference<CountDownLatch> publishLatch = new AtomicReference<>(new CountDownLatch(1));
        client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(metaHandshake, handshake) -> {
            if (handshake.isSuccessful()) {
                client.getChannel(channelName).subscribe((channel, message) -> publishLatch.get().countDown());
            }
        });
        AtomicReference<CountDownLatch> connectLatch = new AtomicReference<>(new CountDownLatch(2));
        client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> connectLatch.get().countDown());
        client.handshake();

        // Wait for the long poll to establish
        Thread.sleep(1000);

        // Test publish triggered by an external event
        LocalSession emitter = bayeux.newLocalSession("test_emitter");
        emitter.handshake();
        String data = "test_data";
        bayeux.getChannel(channelName).publish(emitter, data, Promise.noop());

        Assertions.assertTrue(publishLatch.get().await(5, TimeUnit.SECONDS));
        // Make sure long poll is not responded
        Assertions.assertFalse(connectLatch.get().await(1, TimeUnit.SECONDS));

        // Test publish triggered by a message sent by the client
        // There will be a response pending so the case is different
        publishLatch.set(new CountDownLatch(1));
        connectLatch.set(new CountDownLatch(1));
        String serviceChannelName = "/service/test";
        ServerChannel serviceChannel = bayeux.createChannelIfAbsent(serviceChannelName, new Persistent()).getReference();
        serviceChannel.addListener(new ServerChannel.MessageListener() {
            @Override
            public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message) {
                bayeux.getChannel(channelName).publish(emitter, data, Promise.noop());
                return true;
            }
        });
        client.getChannel(serviceChannelName).publish(new HashMap<>());

        Assertions.assertTrue(publishLatch.get().await(5, TimeUnit.SECONDS));
        // Make sure long poll is not responded
        Assertions.assertFalse(connectLatch.get().await(1, TimeUnit.SECONDS));

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testMetaConnectDeliveryOnlyTransport(String wsType) throws Exception {
        Map<String, String> options = new HashMap<>();
        options.put(AbstractServerTransport.META_CONNECT_DELIVERY_OPTION, "true");
        prepareAndStart(wsType, options);

        BayeuxClient client = newBayeuxClient(wsType);

        String channelName = "/test";
        AtomicReference<CountDownLatch> publishLatch = new AtomicReference<>(new CountDownLatch(1));
        client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(metaHandshake, handshake) -> {
            if (handshake.isSuccessful()) {
                client.getChannel(channelName).subscribe((channel, message) -> publishLatch.get().countDown());
            }
        });
        AtomicReference<CountDownLatch> connectLatch = new AtomicReference<>(new CountDownLatch(2));
        client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> connectLatch.get().countDown());
        client.handshake();

        // Wait for the long poll to establish
        Thread.sleep(1000);

        // Test publish triggered by an external event
        LocalSession emitter = bayeux.newLocalSession("test_emitter");
        emitter.handshake();
        String data = "test_data";
        bayeux.getChannel(channelName).publish(emitter, data, Promise.noop());

        Assertions.assertTrue(publishLatch.get().await(5, TimeUnit.SECONDS));
        // Make sure long poll is responded
        Assertions.assertTrue(connectLatch.get().await(5, TimeUnit.SECONDS));

        // Test publish triggered by a message sent by the client
        // There will be a response pending so the case is different
        // from the server-side publish
        publishLatch.set(new CountDownLatch(1));
        connectLatch.set(new CountDownLatch(1));
        String serviceChannelName = "/service/test";
        ServerChannel serviceChannel = bayeux.createChannelIfAbsent(serviceChannelName, new Persistent()).getReference();
        serviceChannel.addListener(new ServerChannel.MessageListener() {
            @Override
            public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message) {
                bayeux.getChannel(channelName).publish(emitter, data, Promise.noop());
                return true;
            }
        });
        client.getChannel(serviceChannelName).publish(new HashMap<>());

        Assertions.assertTrue(publishLatch.get().await(5, TimeUnit.SECONDS));
        // Make sure long poll is responded
        Assertions.assertTrue(connectLatch.get().await(5, TimeUnit.SECONDS));

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testMetaConnectDeliveryOnlySession(String wsType) throws Exception {
        prepareAndStart(wsType, null);

        bayeux.addExtension(new BayeuxServer.Extension() {
            @Override
            public boolean sendMeta(ServerSession to, ServerMessage.Mutable message) {
                if (Channel.META_HANDSHAKE.equals(message.getChannel())) {
                    if (to != null && !to.isLocalSession()) {
                        to.setMetaConnectDeliveryOnly(true);
                    }
                }
                return true;
            }
        });

        BayeuxClient client = newBayeuxClient(wsType);

        String channelName = "/test";
        AtomicReference<CountDownLatch> publishLatch = new AtomicReference<>(new CountDownLatch(1));
        client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(metaHandshake, handshake) -> {
            if (handshake.isSuccessful()) {
                client.getChannel(channelName).subscribe((channel, message) -> publishLatch.get().countDown());
            }
        });
        AtomicReference<CountDownLatch> connectLatch = new AtomicReference<>(new CountDownLatch(2));
        client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> connectLatch.get().countDown());
        client.handshake();

        // Wait for the long poll to establish
        Thread.sleep(1000);

        // Test publish triggered by an external event
        LocalSession emitter = bayeux.newLocalSession("test_emitter");
        emitter.handshake();
        String data = "test_data";
        bayeux.getChannel(channelName).publish(emitter, data, Promise.noop());

        Assertions.assertTrue(publishLatch.get().await(5, TimeUnit.SECONDS));
        // Make sure long poll is responded
        Assertions.assertTrue(connectLatch.get().await(5, TimeUnit.SECONDS));

        // Test publish triggered by a message sent by the client
        // There will be a response pending so the case is different
        publishLatch.set(new CountDownLatch(1));
        connectLatch.set(new CountDownLatch(1));
        String serviceChannelName = "/service/test";
        ServerChannel serviceChannel = bayeux.createChannelIfAbsent(serviceChannelName, new Persistent()).getReference();
        serviceChannel.addListener(new ServerChannel.MessageListener() {
            @Override
            public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message) {
                bayeux.getChannel(channelName).publish(emitter, data, Promise.noop());
                return true;
            }
        });
        client.getChannel(serviceChannelName).publish(new HashMap<>());

        Assertions.assertTrue(publishLatch.get().await(5, TimeUnit.SECONDS));
        // Make sure long poll is responded
        Assertions.assertTrue(connectLatch.get().await(5, TimeUnit.SECONDS));

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testMetaConnectExpires(String wsType) throws Exception {
        long timeout = 2000;
        Map<String, String> options = new HashMap<>();
        options.put(AbstractServerTransport.TIMEOUT_OPTION, String.valueOf(timeout));
        prepareAndStart(wsType, options);

        BayeuxClient client = newBayeuxClient(wsType);
        CountDownLatch connectLatch = new CountDownLatch(2);
        client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            connectLatch.countDown();
            if (connectLatch.getCount() == 0) {
                client.disconnect();
            }
        });
        CountDownLatch disconnectLatch = new CountDownLatch(1);
        client.getChannel(Channel.META_DISCONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> disconnectLatch.countDown());
        client.handshake();

        Assertions.assertTrue(connectLatch.await(timeout + timeout / 2, TimeUnit.MILLISECONDS));
        Assertions.assertTrue(disconnectLatch.await(5, TimeUnit.SECONDS));
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testWebSocketWithAckExtension(String wsType) throws Exception {
        prepareAndStart(wsType, null);

        BayeuxClient client = newBayeuxClient(wsType);

        bayeux.addExtension(new AcknowledgedMessagesExtension());
        client.addExtension(new AckExtension());

        String channelName = "/chat/demo";
        BlockingQueue<Message> messages = new BlockingArrayQueue<>();
        client.getChannel(Channel.META_HANDSHAKE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            if (message.isSuccessful()) {
                client.getChannel(channelName).subscribe((c, m) -> messages.add(m));
            }
        });
        CountDownLatch subscribed = new CountDownLatch(1);
        client.getChannel(Channel.META_SUBSCRIBE).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            if (message.isSuccessful() && channelName.equals(message.get(Message.SUBSCRIPTION_FIELD))) {
                subscribed.countDown();
            }
        });
        client.handshake();

        Assertions.assertTrue(subscribed.await(5, TimeUnit.SECONDS));
        Assertions.assertEquals(0, messages.size());

        ServerChannel chatChannel = bayeux.getChannel(channelName);
        Assertions.assertNotNull(chatChannel);

        int count = 5;
        client.batch(() -> {
            for (int i = 0; i < count; ++i) {
                client.getChannel(channelName).publish("hello_" + i);
            }
        });

        for (int i = 0; i < count; ++i) {
            Assertions.assertEquals("hello_" + i, messages.poll(5, TimeUnit.SECONDS).getData());
        }

        // Give time to the /meta/connect to tell the server what is the current ack number
        Thread.sleep(1000);

        int port = connector.getLocalPort();
        connector.stop();
        Thread.sleep(1000);
        Assertions.assertTrue(connector.isStopped());
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.UNCONNECTED));

        // Send messages while client is offline
        for (int i = count; i < 2 * count; ++i) {
            chatChannel.publish(null, "hello_" + i, Promise.noop());
        }

        Thread.sleep(1000);
        Assertions.assertEquals(0, messages.size());

        connector.setPort(port);
        connector.start();
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));

        // Check that the offline messages are received
        for (int i = count; i < 2 * count; ++i) {
            Assertions.assertEquals("hello_" + i, messages.poll(5, TimeUnit.SECONDS).getData());
        }

        // Send messages while client is online
        client.batch(() -> {
            for (int i = 2 * count; i < 3 * count; ++i) {
                client.getChannel(channelName).publish("hello_" + i);
            }
        });

        // Check if messages after reconnect are received
        for (int i = 2 * count; i < 3 * count; ++i) {
            Assertions.assertEquals("hello_" + i, messages.poll(5, TimeUnit.SECONDS).getData());
        }

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testMetaConnectDelayedOnServerRespondedBeforeRetry(String wsType) throws Exception {
        long maxNetworkDelay = 2000;
        long backoffIncrement = 2000;
        testMetaConnectDelayedOnServer(wsType, maxNetworkDelay, backoffIncrement, maxNetworkDelay + backoffIncrement / 2);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testMetaConnectDelayedOnServerRespondedAfterRetry(String wsType) throws Exception {
        long maxNetworkDelay = 2000;
        long backoffIncrement = 1000;
        testMetaConnectDelayedOnServer(wsType, maxNetworkDelay, backoffIncrement, maxNetworkDelay + backoffIncrement * 2);
    }

    private void testMetaConnectDelayedOnServer(String wsType, long maxNetworkDelay, long backoffIncrement, long delay) throws Exception {
        stopAndDispose();

        Map<String, String> initParams = new HashMap<>();
        long timeout = 5000;
        initParams.put("timeout", String.valueOf(timeout));
        switch (wsType) {
            case WEBSOCKET_JSR356:
            case WEBSOCKET_OKHTTP:
                initParams.put("transports", CloseLatchWebSocketTransport.class.getName() + "," + JSONTransport.class.getName());
                break;
            case WEBSOCKET_JETTY:
                initParams.put("transports", CloseLatchJettyWebSocketTransport.class.getName() + "," + JSONTransport.class.getName());
                break;
            default:
                throw new IllegalArgumentException();
        }
        prepareAndStart(wsType, initParams);

        Map<String, Object> options = new HashMap<>();
        options.put("ws.maxNetworkDelay", maxNetworkDelay);
        ClientTransport webSocketTransport = newWebSocketTransport(wsType, options);
        BayeuxClient client = new BayeuxClient(cometdURL, webSocketTransport);
        client.setOption(BayeuxClient.BACKOFF_INCREMENT_OPTION, backoffIncrement);

        bayeux.getChannel(Channel.META_CONNECT).addListener(new ServerChannel.MessageListener() {
            private final AtomicInteger connects = new AtomicInteger();

            @Override
            public boolean onMessage(ServerSession from, ServerChannel channel, ServerMessage.Mutable message) {
                int connects = this.connects.incrementAndGet();
                if (connects == 2) {
                    try {
                        // We delay the second connect, so the client can expire it
                        Thread.sleep(delay);
                    } catch (InterruptedException x) {
                        x.printStackTrace();
                        return false;
                    }
                }
                return true;
            }
        });

        // The second connect must fail, and should never be notified on client
        CountDownLatch connectLatch1 = new CountDownLatch(2);
        CountDownLatch connectLatch2 = new CountDownLatch(1);
        client.getChannel(Channel.META_CONNECT).addListener(new ClientSessionChannel.MessageListener() {
            private final AtomicInteger connects = new AtomicInteger();
            public String failedId;

            @Override
            public void onMessage(ClientSessionChannel channel, Message message) {
                int connects = this.connects.incrementAndGet();
                if (connects == 1 && message.isSuccessful()) {
                    connectLatch1.countDown();
                } else if (connects == 2 && !message.isSuccessful()) {
                    connectLatch1.countDown();
                    failedId = message.getId();
                } else if (connects > 2 && !failedId.equals(message.getId())) {
                    connectLatch2.countDown();
                }
            }
        });

        client.handshake();

        Assertions.assertTrue(connectLatch1.await(timeout + 2 * maxNetworkDelay, TimeUnit.MILLISECONDS));
        Assertions.assertTrue(connectLatch2.await(backoffIncrement * 2, TimeUnit.MILLISECONDS));

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testClientSendsAndReceivesBigMessage(String wsType) throws Exception {
        int maxMessageSize = 128 * 1024;
        Map<String, String> serverOptions = new HashMap<>();
        serverOptions.put("ws.maxMessageSize", String.valueOf(maxMessageSize));
        prepareAndStart(wsType, serverOptions);

        Map<String, Object> clientOptions = new HashMap<>();
        clientOptions.put("ws.maxMessageSize", maxMessageSize);
        ClientTransport webSocketTransport = newWebSocketTransport(wsType, clientOptions);
        BayeuxClient client = new BayeuxClient(cometdURL, webSocketTransport);

        client.handshake();
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));

        ClientSessionChannel channel = client.getChannel("/test");
        CountDownLatch latch = new CountDownLatch(1);
        channel.subscribe((c, m) -> latch.countDown());

        char[] data = new char[maxMessageSize * 3 / 4];
        Arrays.fill(data, 'x');
        channel.publish(new String(data));

        Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS));

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testClientDisconnectingClosesTheConnection(String wsType) throws Exception {
        Map<String, String> initParams = new HashMap<>();
        switch (wsType) {
            case WEBSOCKET_JSR356:
            case WEBSOCKET_OKHTTP:
                initParams.put("transports", CloseLatchWebSocketTransport.class.getName() + "," + JSONTransport.class.getName());
                break;
            case WEBSOCKET_JETTY:
                initParams.put("transports", CloseLatchJettyWebSocketTransport.class.getName() + "," + JSONTransport.class.getName());
                break;
            default:
                throw new IllegalArgumentException();
        }
        prepareAndStart(wsType, initParams);

        BayeuxClient client = newBayeuxClient(wsType);
        client.handshake();
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));
        Thread.sleep(1000);

        client.disconnect();

        switch (wsType) {
            case WEBSOCKET_JSR356:
            case WEBSOCKET_OKHTTP:
                CloseLatchWebSocketTransport jsrTransport = (CloseLatchWebSocketTransport)bayeux.getTransport("websocket");
                Assertions.assertTrue(jsrTransport.latch.await(5, TimeUnit.SECONDS));
                break;
            case WEBSOCKET_JETTY:
                CloseLatchJettyWebSocketTransport jettyTransport = (CloseLatchJettyWebSocketTransport)bayeux.getTransport("websocket");
                Assertions.assertTrue(jettyTransport.latch.await(5, TimeUnit.SECONDS));
                break;
            default:
                throw new IllegalArgumentException();
        }
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testClientDisconnectingSynchronouslyClosesTheConnection(String wsType) throws Exception {
        Map<String, String> initParams = new HashMap<>();
        switch (wsType) {
            case WEBSOCKET_JSR356:
            case WEBSOCKET_OKHTTP:
                initParams.put("transports", CloseLatchWebSocketTransport.class.getName() + "," + JSONTransport.class.getName());
                break;
            case WEBSOCKET_JETTY:
                initParams.put("transports", CloseLatchJettyWebSocketTransport.class.getName() + "," + JSONTransport.class.getName());
                break;
            default:
                throw new IllegalArgumentException();
        }
        prepareAndStart(wsType, initParams);

        BayeuxClient client = newBayeuxClient(wsType);
        client.handshake();
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));
        Thread.sleep(1000);

        client.disconnect(1000);

        switch (wsType) {
            case WEBSOCKET_JSR356:
            case WEBSOCKET_OKHTTP:
                CloseLatchWebSocketTransport jsrTransport = (CloseLatchWebSocketTransport)bayeux.getTransport("websocket");
                Assertions.assertTrue(jsrTransport.latch.await(5, TimeUnit.SECONDS));
                break;
            case WEBSOCKET_JETTY:
                CloseLatchJettyWebSocketTransport jettyTransport = (CloseLatchJettyWebSocketTransport)bayeux.getTransport("websocket");
                Assertions.assertTrue(jettyTransport.latch.await(5, TimeUnit.SECONDS));
                break;
            default:
                throw new IllegalArgumentException();
        }
    }

    public static class CloseLatchWebSocketTransport extends WebSocketTransport {
        private final CountDownLatch latch = new CountDownLatch(1);

        public CloseLatchWebSocketTransport(BayeuxServerImpl bayeux) {
            super(bayeux);
        }

        @Override
        protected void onClose(int code, String reason) {
            latch.countDown();
        }
    }

    public static class CloseLatchJettyWebSocketTransport extends org.cometd.server.websocket.jetty.JettyWebSocketTransport {
        private final CountDownLatch latch = new CountDownLatch(1);

        public CloseLatchJettyWebSocketTransport(BayeuxServerImpl bayeux) {
            super(bayeux);
        }

        @Override
        protected void onClose(int code, String reason) {
            latch.countDown();
        }
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testWhenClientAbortsServerSessionIsSwept(String wsType) throws Exception {
        Map<String, String> options = new HashMap<>();
        long timeout = 2000;
        long maxInterval = 1000;
        options.put(AbstractServerTransport.TIMEOUT_OPTION, String.valueOf(timeout));
        options.put(AbstractServerTransport.MAX_INTERVAL_OPTION, String.valueOf(maxInterval));
        prepareAndStart(wsType, options);

        BayeuxClient client = newBayeuxClient(wsType);
        client.handshake();
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));

        // Allow the /meta/connect to be held.
        Thread.sleep(1000);

        CountDownLatch latch = new CountDownLatch(1);
        ServerSession session = bayeux.getSession(client.getId());
        session.addListener((ServerSession.RemovedListener)(s, m, t) -> latch.countDown());

        client.abort();

        Assertions.assertTrue(latch.await(timeout + 2 * maxInterval, TimeUnit.MILLISECONDS));
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testDisconnectWithPendingMetaConnectWithoutResponseIsFailedOnClient(String wsType) throws Exception {
        long timeout = 2000L;
        Map<String, String> serverOptions = new HashMap<>();
        serverOptions.put("timeout", String.valueOf(timeout));
        prepareAndStart(wsType, serverOptions);

        bayeux.addExtension(new BayeuxServer.Extension() {
            @Override
            public boolean sendMeta(ServerSession to, ServerMessage.Mutable message) {
                if (Channel.META_CONNECT.equals(message.getChannel())) {
                    Map<String, Object> advice = message.getAdvice();
                    if (advice != null) {
                        if (Message.RECONNECT_NONE_VALUE.equals(advice.get(Message.RECONNECT_FIELD))) {
                            // Pretend this message could not be sent
                            return false;
                        }
                    }
                }
                return true;
            }
        });

        long maxNetworkDelay = 2000L;
        Map<String, Object> clientOptions = new HashMap<>();
        clientOptions.put("maxNetworkDelay", maxNetworkDelay);
        ClientTransport webSocketTransport = newWebSocketTransport(wsType, clientOptions);
        BayeuxClient client = new BayeuxClient(cometdURL, webSocketTransport);

        client.handshake();
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));

        // Wait for the /meta/connect to be held on server
        TimeUnit.MILLISECONDS.sleep(1000);

        CountDownLatch latch = new CountDownLatch(1);
        client.getChannel(Channel.META_CONNECT).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            if (!message.isSuccessful()) {
                latch.countDown();
            }
        });

        client.disconnect();

        // Only wait for the maxNetworkDelay: when the /meta/disconnect response arrives,
        // the connection is closed, so the /meta/connect is failed on the client side.
        Assertions.assertTrue(latch.await(2 * maxNetworkDelay, TimeUnit.MILLISECONDS));
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testDeliverDuringHandshakeProcessing(String wsType) throws Exception {
        prepareAndStart(wsType, null);

        String channelName = "/service/test";
        BayeuxClient client = newBayeuxClient(wsType);

        CountDownLatch latch = new CountDownLatch(1);
        client.getChannel(channelName).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            if (!message.isPublishReply()) {
                latch.countDown();
            }
        });

        // SessionListener is the first listener notified after the ServerSession is created.
        bayeux.addListener(new BayeuxServer.SessionListener() {
            @Override
            public void sessionAdded(ServerSession session, ServerMessage message) {
                session.deliver(null, channelName, "data", Promise.noop());
            }
        });

        client.handshake();
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));

        Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS));

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testDeliverDuringHandshakeProcessingWithAckExtension(String wsType) throws Exception {
        prepareAndStart(wsType, null);

        bayeux.addExtension(new AcknowledgedMessagesExtension());

        String channelName = "/service/test";
        BayeuxClient client = newBayeuxClient(wsType);
        client.addExtension(new AckExtension());

        CountDownLatch latch = new CountDownLatch(1);
        client.getChannel(channelName).addListener((ClientSessionChannel.MessageListener)(channel, message) -> {
            if (!message.isPublishReply()) {
                latch.countDown();
            }
        });

        // SessionListener is the first listener notified after the ServerSession is created.
        bayeux.addListener(new BayeuxServer.SessionListener() {
            @Override
            public void sessionAdded(ServerSession session, ServerMessage message) {
                session.deliver(null, channelName, "data", Promise.noop());
            }
        });

        client.handshake();
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));

        Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS));

        disconnectBayeuxClient(client);
    }

    @ParameterizedTest
    @MethodSource("wsTypes")
    public void testExtensionIsInvokedAfterNetworkFailure(String wsType) throws Exception {
        // No way to stop OkHttpClient.
        Assumptions.assumeFalse(wsType.equals(WEBSOCKET_OKHTTP));

        prepareAndStart(wsType, null);

        bayeux.addExtension(new AcknowledgedMessagesExtension());

        BayeuxClient client = newBayeuxClient(wsType);
        String channelName = "/test";
        AtomicReference<CountDownLatch> rcv = new AtomicReference<>(new CountDownLatch(1));
        client.addExtension(new AckExtension());
        client.addExtension(new ClientSession.Extension() {
            @Override
            public boolean rcv(ClientSession session, Message.Mutable message) {
                if (channelName.equals(message.getChannel())) {
                    rcv.get().countDown();
                }
                return true;
            }
        });
        client.handshake(message -> client.getChannel(channelName).subscribe((c, m) -> {
        }));
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));

        // This message will be delivered via /meta/connect.
        bayeux.createChannelIfAbsent(channelName).getReference().publish(null, "data1", Promise.noop());
        Assertions.assertTrue(rcv.get().await(5, TimeUnit.SECONDS));
        // Wait for the /meta/connect to be established again.
        Thread.sleep(1000);

        // Stopping HttpClient will also stop the WebSocketClients (both Jetty's and JSR's).
        httpClient.stop();
        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.UNCONNECTED));

        // Send a message while disconnected.
        bayeux.createChannelIfAbsent(channelName).getReference().publish(null, "data2", Promise.noop());

        rcv.set(new CountDownLatch(1));
        httpClient.start();

        Assertions.assertTrue(client.waitFor(5000, BayeuxClient.State.CONNECTED));
        Assertions.assertTrue(rcv.get().await(5, TimeUnit.SECONDS));

        disconnectBayeuxClient(client);
    }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ShopBundle\Twig;

use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\OrderItem;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

final class OrderItemOriginalPriceToDisplayExtension extends AbstractExtension
{
    public function getFunctions(): array
    {
        return [
            new TwigFunction('sylius_order_item_original_price_to_display', [$this, 'getOriginalPriceToDisplay']),
        ];
    }

    public function getOriginalPriceToDisplay(OrderItem $item, ChannelInterface $channel): ?int
    {
        $variant = $item->getVariant();

        $channelPricing = $variant->getChannelPricingForChannel($channel);
        $originalPrice = $channelPricing->getOriginalPrice();
        $price = $channelPricing->getPrice();

        $regularPrice = $item->getUnitPrice();
        $discountedPrice = $item->getDiscountedUnitPrice();

        if ($originalPrice !== null && $originalPrice > $price) {
            return $originalPrice;
        }

        if ($originalPrice === null && $regularPrice > $discountedPrice) {
            return $regularPrice;
        }

        return null;
    }
}


text:
/*************************************************************************/
/*  skeleton_ik.h                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef SKELETON_IK_H
#define SKELETON_IK_H

#ifndef _3D_DISABLED

/**
 * @author AndreaCatania
 */

#include "core/math/transform.h"
#include "scene/3d/skeleton.h"

class FabrikInverseKinematic {

	struct EndEffector {
		BoneId tip_bone;
		Transform goal_transform;
	};

	struct ChainItem {

		Vector<ChainItem> childs;
		ChainItem *parent_item;

		// Bone info
		BoneId bone;
		PhysicalBone *pb;

		real_t length;
		/// Positions relative to root bone
		Transform initial_transform;
		Vector3 current_pos;
		// Direction from this bone to child
		Vector3 current_ori;

		ChainItem() :
				parent_item(NULL),
				bone(-1),
				pb(NULL),
				length(0) {}

		ChainItem *find_child(const BoneId p_bone_id);
		ChainItem *add_child(const BoneId p_bone_id);
	};

	struct ChainTip {
		ChainItem *chain_item;
		const EndEffector *end_effector;

		ChainTip() :
				chain_item(NULL),
				end_effector(NULL) {}

		ChainTip(ChainItem *p_chain_item, const EndEffector *p_end_effector) :
				chain_item(p_chain_item),
				end_effector(p_end_effector) {}

		ChainTip(const ChainTip &p_other_ct) :
				chain_item(p_other_ct.chain_item),
				end_effector(p_other_ct.end_effector) {}
	};

	struct Chain {
		ChainItem chain_root;
		ChainItem *middle_chain_item;
		Vector<ChainTip> tips;
		Vector3 magnet_position;
	};

public:
	struct Task : public RID_Data {
		RID self;
		Skeleton *skeleton;

		Chain chain;

		// Settings
		real_t min_distance;
		int max_iterations;

		// Bone data
		BoneId root_bone;
		Vector<EndEffector> end_effectors;

		Transform goal_global_transform;

		Task() :
				skeleton(NULL),
				min_distance(0.01),
				max_iterations(10),
				root_bone(-1) {}
	};

private:
	/// Init a chain that starts from the root to tip
	static bool build_chain(Task *p_task, bool p_force_simple_chain = true);

	static void update_chain(const Skeleton *p_sk, ChainItem *p_chain_item);

	static void solve_simple(Task *p_task, bool p_solve_magnet);
	/// Special solvers that solve only chains with one end effector
	static void solve_simple_backwards(Chain &r_chain, bool p_solve_magnet);
	static void solve_simple_forwards(Chain &r_chain, bool p_solve_magnet);

public:
	static Task *create_simple_task(Skeleton *p_sk, BoneId root_bone, BoneId tip_bone, const Transform &goal_transform);
	static void free_task(Task *p_task);
	// The goal of chain should be always in local space
	static void set_goal(Task *p_task, const Transform &p_goal);
	static void make_goal(Task *p_task, const Transform &p_inverse_transf, real_t blending_delta);
	static void solve(Task *p_task, real_t blending_delta, bool override_tip_basis, bool p_use_magnet, const Vector3 &p_magnet_position);
};

class SkeletonIK : public Node {
	GDCLASS(SkeletonIK, Node);

	StringName root_bone;
	StringName tip_bone;
	real_t interpolation;
	Transform target;
	NodePath target_node_path_override;
	bool override_tip_basis;
	bool use_magnet;
	Vector3 magnet_position;

	real_t min_distance;
	int max_iterations;

	Skeleton *skeleton;
	Spatial *target_node_override;
	FabrikInverseKinematic::Task *task;

protected:
	virtual void
	_validate_property(PropertyInfo &property) const;

	static void _bind_methods();
	virtual void _notification(int p_notification);

public:
	SkeletonIK();
	virtual ~SkeletonIK();

	void set_root_bone(const StringName &p_root_bone);
	StringName get_root_bone() const;

	void set_tip_bone(const StringName &p_tip_bone);
	StringName get_tip_bone() const;

	void set_interpolation(real_t p_interpolation);
	real_t get_interpolation() const;

	void set_target_transform(const Transform &p_target);
	const Transform &get_target_transform() const;

	void set_target_node(const NodePath &p_node);
	NodePath get_target_node();

	void set_override_tip_basis(bool p_override);
	bool is_override_tip_basis() const;

	void set_use_magnet(bool p_use);
	bool is_using_magnet() const;

	void set_magnet_position(const Vector3 &p_constraint);
	const Vector3 &get_magnet_position() const;

	void set_min_distance(real_t p_min_distance);
	real_t get_min_distance() const { return min_distance; }

	void set_max_iterations(int p_iterations);
	int get_max_iterations() const { return max_iterations; }

	Skeleton *get_parent_skeleton() const { return skeleton; }

	bool is_running();

	void start(bool p_one_time = false);
	void stop();

private:
	Transform _get_target_transform();
	void reload_chain();
	void reload_goal();
	void _solve_chain();
};

#endif // _3D_DISABLED

#endif // SKELETON_IK_H


text:
const pgp = require('pg-promise')()
const connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/taskDatabase'
const db = pgp(connectionString)

const getAll = () => {
  const sql = `SELECT * FROM tasks ORDER BY ordering ASC`
  return db.any(sql)
}

const add = () => {
  const sql = `
    INSERT INTO tasks (text)
    VALUES ($1)
    RETURNING id
  `
  return db.one(sql, [''])
}

const markAsComplete = (id) => {
  const sql = `
    UPDATE tasks
    SET completed = true
    WHERE id = $1
  `
  return db.none(sql, [id])
}

const markAsIncomplete = (id) => {
  const sql = `
    UPDATE tasks
    SET completed = false
    WHERE id = $1
  `
  return db.none(sql, [id])
}

const edit = (id, text) => {
  const sql = `
    UPDATE tasks
    SET text = $2
    WHERE id = $1
  `
  return db.none(sql, [id, text])
}

const remove = (id) => {
  const sql = `
    DELETE FROM tasks
    WHERE id = $1
  `
  return db.none(sql, [id])
}

const getOrdering = id => {
  const sql = `
    SELECT ordering FROM tasks
    WHERE id = $1
  `
  return db.one(sql, [id])
}

const setOrdering = (id, ordering) => {
  const sql = `
    UPDATE tasks
    SET ordering = $2
    WHERE id = $1
  `
  return db.none(sql, [id, ordering])
}

const reorder = (id1, id2) => {
  let ordering1, ordering2
  return Promise.all([
    getOrdering(id1),
    getOrdering(id2)
  ])
  .then( results => {
    ordering1 = results[0].ordering
    ordering2 = results[1].ordering
    setOrdering(id1, 0)
  })
  .then( () => {
    setOrdering(id2, ordering1)
  })
  .then( () => {
    setOrdering(id1, ordering2)
  })
}

module.exports = {
  getAll,
  add,
  markAsComplete,
  markAsIncomplete,
  edit,
  remove,
  reorder,
}


text:
package one.two;

public class Write {
    public static void main(String[] args) {
        KotlinClass.setStaticExtensionVariable(4, 3);
    }
}


text: {% extends "userena/base_userena.html" %}


text:
package bboss.org.artofsolving.jodconverter.office;

public enum OfficeConnectionProtocol { PIPE, SOCKET }


text:
using System;
using System.IO;

namespace Public.Common.Lib.Code
{
    /// <summary>
    /// Used in determining which projects need to be distributed between solutions.
    /// </summary>
    /// <remarks>
    /// For a Visual Studio versioned project file name, we do not want to use the GUID to determine the identity of a project.
    /// Instead, we want to use the base-file named relative path.
    ///
    /// For a project file name without a Visual Studio version token, we want to use the GUID.
    /// </remarks>
    public class ProjectReferenceDiffItem : IEquatable<ProjectReferenceDiffItem>
    {
        #region Static

        public static bool operator ==(ProjectReferenceDiffItem lhs, ProjectReferenceDiffItem rhs)
        {
            if (object.ReferenceEquals(null, lhs))
            {
                if (object.ReferenceEquals(null, rhs))
                {
                    return true;
                }

                return false;
            }

            return lhs.Equals(rhs); // Equals() handles a null right side.
        }

        public static bool operator !=(ProjectReferenceDiffItem lhs, ProjectReferenceDiffItem rhs)
        {
            return !(lhs == rhs);
        }

        private static int GetInstanceHashValue(ProjectReferenceDiffItem item)
        {
            int output;
            if(VisualStudioVersionSet.IsVisualStudioVersioned(item.RelativePath))
            {
                string fileNameBase = ProjectFileNameInfo.GetFileNameBase(item.RelativePath);

                string directoryName = Path.GetDirectoryName(item.RelativePath);
                string baseFileNamePath = Path.Combine(directoryName, fileNameBase);

                output = baseFileNamePath.GetHashCode();
            }
            else
            {
                output = item.GUID.GetHashCode();
            }

            return output;
        }

        #endregion

        #region IEquatable<ProjectReferenceDiffItem> Members

        public bool Equals(ProjectReferenceDiffItem other)
        {
            if (object.ReferenceEquals(null, other))
            {
                return false;
            }

            if (object.ReferenceEquals(this, other))
            {
                return true;
            }

            if (this.GetType() != other.GetType())
            {
                return false;
            }

#if DEBUG
            bool output = true;
            output = output && (this.HashValue == other.HashValue);

            return output;
#else
            return
                (this.HashValue == other.HashValue);
#endif
        }

        #endregion

        public string RelativePath { get; set; }
        public Guid GUID { get; set; }
        public int HashValue { get; set; }

        public ProjectReferenceDiffItem(string relativePath, Guid guid)
        {
            this.RelativePath = relativePath;
            this.GUID = guid;

            this.HashValue = ProjectReferenceDiffItem.GetInstanceHashValue(this);
        }

        public override bool Equals(object obj)
        {
            return this.Equals(obj as ProjectReferenceDiffItem);
        }

        public override int GetHashCode()
        {
            return this.HashValue;
        }
    }
}


text:
using System;
using System.Text;
/// <summary>
/// StringBuilder.ctor(String,Int32)
/// </summary>
public class StringBuilderctor5
{
    public static int Main()
    {
        StringBuilderctor5 sbctor5 = new StringBuilderctor5();
        TestLibrary.TestFramework.BeginTestCase("StringBuilderctor5");
        if (sbctor5.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }
    public bool RunTests()
    {
        bool retVal = true;
        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;
        retVal = PosTest2() && retVal;
        retVal = PosTest3() && retVal;
        retVal = PosTest4() && retVal;
        retVal = PosTest5() && retVal;
        TestLibrary.TestFramework.LogInformation("[Negative]");
        retVal = NegTest1() && retVal;
        return retVal;
    }
    #region PositiveTest
    public bool PosTest1()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest1:Initialize StringBuilder with capacity and string 1");
        try
        {
            string strValue = null;
            int capacity = this.GetInt32(1, 256);
            StringBuilder sb = new StringBuilder(strValue, capacity);
            if (sb == null)
            {
                TestLibrary.TestFramework.LogError("007.1", "StringBuilder was null");
                retVal = false;
            }
            else if (!sb.ToString().Equals(String.Empty))
            {
                TestLibrary.TestFramework.LogError("007.2", "Expected value of StringBuilder.ToString = String.Empty, actual: " +
                    sb.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
            retVal = false;
        }
        return retVal;
    }
    public bool PosTest2()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest2:Initialize StringBuilder with capacity and string 2");
        try
        {
            string strValue = string.Empty;
            int capacity = this.GetInt32(1, 256);
            StringBuilder sb = new StringBuilder(strValue, capacity);
            if (sb == null)
            {
                TestLibrary.TestFramework.LogError("003.1", "StringBuilder was null");
                retVal = false;
            }
            else if (!sb.ToString().Equals(strValue))
            {
                TestLibrary.TestFramework.LogError("003.2", "Expected value of StringBuilder.ToString = " + strValue + ", actual: " +
                    sb.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
            retVal = false;
        }
        return retVal;
    }
    public bool PosTest3()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest3:Initialize StringBuilder with capacity and string 3");
        try
        {
            string strValue = TestLibrary.Generator.GetString(-55, false, 8, 256);
            int capacity = this.GetInt32(1, strValue.Length);
            StringBuilder sb = new StringBuilder(strValue, capacity);
            if (sb == null)
            {
                TestLibrary.TestFramework.LogError("005.1", "StringBuilder was null");
                retVal = false;
            }
            else if (!sb.ToString().Equals(strValue))
            {
                TestLibrary.TestFramework.LogError("005.2", "Expected value of StringBuilder.ToString = " + strValue + ", actual: " +
                    sb.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
            retVal = false;
        }
        return retVal;
    }
    public bool PosTest4()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest4:Initialize StringBuilder with capacity and string 4");
        try
        {
            string strValue = string.Empty;
            int capacity = 0;
            StringBuilder sb = new StringBuilder(strValue, capacity);
            if (sb == null)
            {
                TestLibrary.TestFramework.LogError("007.1", "StringBuilder was null");
                retVal = false;
            }
            else if (!sb.ToString().Equals(strValue))
            {
                TestLibrary.TestFramework.LogError("007.2", "Expected value of StringBuilder.ToString = " + strValue + ", actual: " +
                    sb.ToString());
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
            retVal = false;
        }
        return retVal;
    }
    public bool PosTest5()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest5:Initialize StringBuilder with capacity and string 5");
        try
        {
            string strValue = TestLibrary.Generator.GetString(-55, false, 8, 256);
            int capacity = 0;
            StringBuilder sb = new StringBuilder(strValue, capacity);
            if (sb == null)
                    {
                TestLibrary.TestFramework.LogError("009.0", "StringBuilder was null");
                retVal = false;
            } else if (!sb.ToString().Equals(strValue))
            {
                TestLibrary.TestFramework.LogError("009.1", "Initializer string was "+strValue+", StringBuilder.ToString returned "+sb.ToString());
                retVal = false;
            }
            else if (sb.Capacity == 0)
            {
                TestLibrary.TestFramework.LogError("009.2", "StringBuilder.Capacity returned 0 for non-empty string");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e);
            retVal = false;
        }
        return retVal;
    }
    #endregion
    #region NegativeTest
    public bool NegTest1()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("NegTest1:The capacity is less than zero");
        try
        {
            string strValue = TestLibrary.Generator.GetString(-55, false, 8, 256);
            int capacity = this.GetInt32(1, Int32.MaxValue) * (-1);
            StringBuilder sb = new StringBuilder(strValue, capacity);
            TestLibrary.TestFramework.LogError("N001", "The capacity is less than zero but not throw exception");
            retVal = false;
        }
        catch (ArgumentOutOfRangeException) { }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
            retVal = false;
        }
        return retVal;
    }
    #endregion
    #region HelpMethod
    private Int32 GetInt32(Int32 minValue, Int32 maxValue)
    {
        try
        {
            if (minValue == maxValue)
            {
                return minValue;
            }
            if (minValue < maxValue)
            {
                return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
            }
        }
        catch
        {
            throw;
        }

        return minValue;
    }
    #endregion
}


text:
using System;

namespace Restall.Nancy.ServiceRouting.Tests.Integration.NamedRouteService
{
	[NamedRoute("SomeNamedRoute: async", "/some-named-async-route/{token}")]
	public class AsyncNamedRouteRequest
	{
		public Guid Token { get; private set; }
	}
}


text:
package jsinterop.base;

import java.util.Arrays;
import java.util.List;
import javaemul.internal.annotations.DoNotAutobox;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

/**
 * Provides abstraction for JavaScript array-like objects.
 *
 * <p>See {@link Js#asArrayLike(Object)} to cast an array-like object to {@code JsArrayLike}.
 */
@JsType(isNative = true, name = "IArrayLike", namespace = JsPackage.GLOBAL)
public interface JsArrayLike<T> {

  @JsOverlay
  default int getLength() {
    return InternalJsUtil.getLength(this);
  }

  @JsOverlay
  default void setLength(int length) {
    InternalJsUtil.setLength(this, length);
  }

  @JsOverlay
  @SuppressWarnings("unchecked")
  default T getAt(int index) {
    return (T) InternalJsUtil.getAt(this, index);
  }

  @JsOverlay
  default Any getAtAsAny(int index) {
    return (Any) InternalJsUtil.getAt(this, index);
  }

  @JsOverlay
  default void setAt(int index, @DoNotAutobox T value) {
    InternalJsUtil.setAt(this, index, value);
  }

  @JsOverlay
  default void delete(int index) {
    InternalJsUtil.deleteAt(this, index);
  }

  @JsOverlay
  default List<T> asList() {
    // Since it is hidden behind Arrays.asList, it is safe to do uncheckedCast.
    T[] asArray = Js.uncheckedCast(this);
    return Arrays.asList(asArray);
  }
}


text:
package com.google.ads.mediation.imobile;

/**
 * Constants for i-mobile mediation adapter.
 */
public final class Constants {

  /**
   * Key of i-mobile publisher ID.
   */
  public static final String KEY_PUBLISHER_ID = "publisherId";

  /**
   * Key of i-mobile media ID.
   */
  public static final String KEY_MEDIA_ID = "mid";

  /**
   * Key of i-mobile spot ID.
   */
  public static final String KEY_SPOT_ID = "asid";

  /**
   * String of call to action.
   */
  public static final String CALL_TO_ACTION = "詳細はこちら";

  /**
   * Restrict instantiation.
   */

  private Constants() {
  }
}


text:
import mock
import unittest

import numpy
import six

from cupy import cuda
from cupy import random
from cupy import testing
from cupy.testing import condition
from cupy.testing import hypothesis

@testing.gpu
class TestRandint(unittest.TestCase):

    _multiprocess_can_split_ = True

    def setUp(self):
        self.rs_tmp = random.generator._random_states
        device_id = cuda.Device().id
        self.m = mock.Mock()
        self.m.interval.return_value = 0
        random.generator._random_states = {device_id: self.m}

    def tearDown(self):
        random.generator._random_states = self.rs_tmp

    def test_value_error(self):
        with self.assertRaises(ValueError):
            random.randint(100, 1)

    def test_high_and_size_are_none(self):
        random.randint(3)
        self.m.interval.assert_called_with(2, None)

    def test_size_is_none(self):
        random.randint(3, 5)
        self.m.interval.assert_called_with(1, None)

    def test_high_is_none(self):
        random.randint(3, None, (1, 2, 3))
        self.m.interval.assert_called_with(2, (1, 2, 3))

    def test_no_none(self):
        random.randint(3, 5, (1, 2, 3))
        self.m.interval.assert_called_with(1, (1, 2, 3))

@testing.gpu
class TestRandint2(unittest.TestCase):

    def setUp(self):
        self.rs_tmp = random.generator._random_states
        random.generator._random_states = {}

    def tearDown(self):
        random.generator._random_states = self.rs_tmp

    @condition.repeat(10)
    def test_within_interval(self):
        val = random.randint(0, 10, (2, 3)).get()
        numpy.testing.assert_array_less(
            numpy.full((2, 3), -1, dtype=numpy.int64), val)
        numpy.testing.assert_array_less(
            val, numpy.full((2, 3), 10, dtype=numpy.int64))

    @condition.retry(20)
    def test_lower_bound(self):
        val = random.randint(0, 2).get()
        self.assertEqual(0, val)

    @condition.retry(20)
    def test_upper_bound(self):
        val = random.randint(0, 2).get()
        self.assertEqual(1, val)

    @condition.retry(5)
    def test_goodness_of_fit(self):
        mx = 5
        trial = 100
        vals = [random.randint(mx).get() for _ in six.moves.xrange(trial)]
        counts = numpy.histogram(vals, bins=numpy.arange(mx + 1))[0]
        expected = numpy.array([float(trial) / mx] * mx)
        self.assertTrue(hypothesis.chi_square_test(counts, expected))

    @condition.retry(5)
    def test_goodness_of_fit_2(self):
        mx = 5
        vals = random.randint(mx, size=(5, 20)).get()
        counts = numpy.histogram(vals, bins=numpy.arange(mx + 1))[0]
        expected = numpy.array([float(vals.size) / mx] * mx)
        self.assertTrue(hypothesis.chi_square_test(counts, expected))

@testing.gpu
class TestRandomIntegers(unittest.TestCase):

    _multiprocess_can_split_ = True

    def setUp(self):
        self.randint_tmp = random.sample_.randint
        random.sample_.randint = mock.Mock()

    def tearDown(self):
        random.sample_.randint = self.randint_tmp

    def test_normal(self):
        random.random_integers(3, 5)
        random.sample_.randint.assert_called_with(3, 6, None)

    def test_high_is_none(self):
        random.random_integers(3, None)
        random.sample_.randint.assert_called_with(1, 4, None)

    def test_size_is_not_none(self):
        random.random_integers(3, 5, (1, 2, 3))
        random.sample_.randint.assert_called_with(3, 6, (1, 2, 3))

@testing.gpu
class TestRandomIntegers2(unittest.TestCase):

    _multiprocess_can_split_ = True

    def setUp(self):
        self.rs_tmp = random.generator._random_states
        random.generator._random_states = {}

    def tearDown(self):
        random.generator._random_states = self.rs_tmp

    @condition.repeat(10)
    def test_within_interval(self):
        val = random.random_integers(0, 10, (2, 3)).get()
        numpy.testing.assert_array_less(
            numpy.full((2, 3), -1, dtype=numpy.int64), val)
        numpy.testing.assert_array_less(
            val, numpy.full((2, 3), 11, dtype=numpy.int64))

    @condition.retry(20)
    def test_lower_bound(self):
        val = random.random_integers(0, 2).get()
        self.assertEqual(0, val)

    @condition.retry(20)
    def test_upper_bound(self):
        val = random.random_integers(0, 2).get()
        self.assertEqual(2, val)

    @condition.retry(5)
    def test_goodness_of_fit(self):
        mx = 5
        trial = 100
        vals = [random.randint(0, mx).get() for _ in six.moves.xrange(trial)]
        counts = numpy.histogram(vals, bins=numpy.arange(mx + 1))[0]
        expected = numpy.array([float(trial) / mx] * mx)
        self.assertTrue(hypothesis.chi_square_test(counts, expected))

    @condition.retry(5)
    def test_goodness_of_fit_2(self):
        mx = 5
        vals = random.randint(0, mx, (5, 20)).get()
        counts = numpy.histogram(vals, bins=numpy.arange(mx + 1))[0]
        expected = numpy.array([float(vals.size) / mx] * mx)
        self.assertTrue(hypothesis.chi_square_test(counts, expected))

@testing.gpu
class TestRandomSample(unittest.TestCase):

    def test_rand(self):
        random.sample_.random_sample = mock.Mock()
        random.rand(1, 2, 3, dtype=numpy.float32)
        random.sample_.random_sample.assert_called_once_with(
            size=(1, 2, 3), dtype=numpy.float32)

    def test_rand_default_dtype(self):
        random.sample_.random_sample = mock.Mock()
        random.rand(1, 2, 3)
        random.sample_.random_sample.assert_called_once_with(
            size=(1, 2, 3), dtype=float)

    def test_rand_invalid_argument(self):
        with self.assertRaises(TypeError):
            random.rand(1, 2, 3, unnecessary='unnecessary_argument')

    def test_randn(self):
        random.distributions.normal = mock.Mock()
        random.randn(1, 2, 3, dtype=numpy.float32)
        random.distributions.normal.assert_called_once_with(
            size=(1, 2, 3), dtype=numpy.float32)

    def test_randn_default_dtype(self):
        random.distributions.normal = mock.Mock()
        random.randn(1, 2, 3)
        random.distributions.normal.assert_called_once_with(
            size=(1, 2, 3), dtype=float)

    def test_randn_invalid_argument(self):
        with self.assertRaises(TypeError):
            random.randn(1, 2, 3, unnecessary='unnecessary_argument')