text:
package org.openqa.selenium.remote.server;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.nullToEmpty;
import static java.util.Collections.list;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import com.google.common.net.HttpHeaders;
import com.google.common.net.MediaType;

import org.openqa.selenium.logging.LoggingHandler;
import org.openqa.selenium.remote.http.HttpMethod;
import org.openqa.selenium.remote.http.HttpRequest;
import org.openqa.selenium.remote.http.HttpResponse;
import org.openqa.selenium.remote.server.xdrpc.CrossDomainRpc;
import org.openqa.selenium.remote.server.xdrpc.CrossDomainRpcLoader;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DriverServlet extends HttpServlet {
  public static final String SESSIONS_KEY = DriverServlet.class.getName() + ".sessions";

  private static final String CROSS_DOMAIN_RPC_PATH = "/xdrpc";

  private final StaticResourceHandler staticResourceHandler = new StaticResourceHandler();

  private final Supplier<DriverSessions> sessionsSupplier;

  private SessionCleaner sessionCleaner;
  private JsonHttpCommandHandler commandHandler;

  public DriverServlet() {
    this.sessionsSupplier = new DriverSessionsSupplier();
  }

  @VisibleForTesting
  DriverServlet(Supplier<DriverSessions> sessionsSupplier) {
    this.sessionsSupplier = sessionsSupplier;
  }

  @Override
  public void init() throws ServletException {
    super.init();

    Logger logger = getLogger();
    logger.addHandler(LoggingHandler.getInstance());

    DriverSessions driverSessions = sessionsSupplier.get();
    commandHandler = new JsonHttpCommandHandler(driverSessions, logger);

    long sessionTimeOutInMs = getValueToUseInMs("webdriver.server.session.timeout", 1800);
    long browserTimeoutInMs = getValueToUseInMs("webdriver.server.browser.timeout", 0);

    if (sessionTimeOutInMs > 0 || browserTimeoutInMs > 0) {
      createSessionCleaner(logger, driverSessions, sessionTimeOutInMs, browserTimeoutInMs);
    }
  }

  @VisibleForTesting
  protected void createSessionCleaner(Logger logger, DriverSessions driverSessions,
                                    long sessionTimeOutInMs, long browserTimeoutInMs) {
    sessionCleaner = new SessionCleaner(driverSessions, logger, sessionTimeOutInMs, browserTimeoutInMs);
    sessionCleaner.start();
  }

  private long getValueToUseInMs(String propertyName, long defaultValue) {
    long time = defaultValue;
    final String property = getServletContext().getInitParameter(propertyName);
    if (property != null) {
      time = Long.parseLong(property);
    }

    return TimeUnit.SECONDS.toMillis(time);
  }

  @Override
  public void destroy() {
    getLogger().removeHandler(LoggingHandler.getInstance());
    if (sessionCleaner != null) {
      sessionCleaner.stopCleaner();
    }
  }

  protected Logger getLogger() {
    return Logger.getLogger(getClass().getName());
  }

  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    if (request.getHeader("Origin") != null) {
      setAccessControlHeaders(response);
    }
    // Make sure our browser-clients never cache responses.
    response.setHeader("Expires", "Thu, 01 Jan 1970 00:00:00 GMT");
    response.setHeader("Cache-Control", "no-cache");
    super.service(request, response);
  }

  /**
   * Sets access control headers to allow cross-origin resource sharing from
   * any origin.
   *
   * @param response The response to modify.
   * @see http://www.w3.org/TR/cors/
   */
  private void setAccessControlHeaders(HttpServletResponse response) {
    response.setHeader("Access-Control-Allow-Origin", "*");  // Real safe.
    response.setHeader("Access-Control-Allow-Methods", "DELETE,GET,HEAD,POST");
    response.setHeader("Access-Control-Allow-Headers", "Accept,Content-Type");
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (request.getPathInfo() == null || "/".equals(request.getPathInfo())) {
      staticResourceHandler.redirectToHub(request, response);
    } else if (staticResourceHandler.isStaticResourceRequest(request)) {
      staticResourceHandler.service(request, response);
    } else {
      handleRequest(request, response);
    }
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    if (CROSS_DOMAIN_RPC_PATH.equalsIgnoreCase(request.getPathInfo())) {
      handleCrossDomainRpc(request, response);
    } else {
      handleRequest(request, response);
    }
  }

  @Override
  protected void doDelete(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    handleRequest(request, response);
  }

  private void handleCrossDomainRpc(
      HttpServletRequest servletRequest, HttpServletResponse servletResponse)
      throws ServletException, IOException {
    CrossDomainRpc rpc;

    try {
      rpc = new CrossDomainRpcLoader().loadRpc(servletRequest);
    } catch (IllegalArgumentException e) {
      servletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      servletResponse.getOutputStream().println(e.getMessage());
      servletResponse.getOutputStream().flush();
      return;
    }

    HttpRequest request = new HttpRequest(
        HttpMethod.valueOf(rpc.getMethod()),
        rpc.getPath());
    request.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString());
    request.setContent(rpc.getContent());

    HttpResponse response = commandHandler.handleRequest(request);
    sendResponse(response, servletResponse);
  }

  protected void handleRequest(
      HttpServletRequest servletRequest, HttpServletResponse servletResponse)
      throws ServletException, IOException {
    HttpRequest request = createInternalRequest(servletRequest);
    HttpResponse response = commandHandler.handleRequest(request);
    sendResponse(response, servletResponse);
  }

  private static HttpRequest createInternalRequest(HttpServletRequest servletRequest)
      throws IOException {
    String path = servletRequest.getPathInfo();
    if (Strings.isNullOrEmpty(path)) {
      path = "/";
    }
    HttpRequest request = new HttpRequest(
        HttpMethod.valueOf(servletRequest.getMethod().toUpperCase()),
        path);

    @SuppressWarnings("unchecked")
    Enumeration<String> headerNames = servletRequest.getHeaderNames();
    for (String name : list(headerNames)) {
      @SuppressWarnings("unchecked")
      Enumeration<String> headerValues = servletRequest.getHeaders(name);
      for (String value : list(headerValues)) {
        request.setHeader(name, value);
      }
    }

    InputStream stream = null;
    try {
      stream = servletRequest.getInputStream();
      request.setContent(ByteStreams.toByteArray(stream));
    } finally {
      if (stream != null) {
        try {
          stream.close();
        } catch (IOException ignored) {
          // Do nothing.
        }
      }
    }

    return request;
  }

  private void sendResponse(HttpResponse response, HttpServletResponse servletResponse)
      throws IOException {
    servletResponse.setStatus(response.getStatus());
    for (String name : response.getHeaderNames()) {
      for (String value : response.getHeaders(name)) {
        servletResponse.addHeader(name, value);
      }
    }
    OutputStream output = servletResponse.getOutputStream();
    output.write(response.getContent());
    output.flush();
    output.close();
  }

  private class DriverSessionsSupplier implements Supplier<DriverSessions> {
    public DriverSessions get() {
      Object attribute = getServletContext().getAttribute(SESSIONS_KEY);
      if (attribute == null) {
        attribute = new DefaultDriverSessions();
      }
      return (DriverSessions) attribute;
    }
  }

  private static class StaticResourceHandler {
    private static final ImmutableMap<String, MediaType> MIME_TYPES = ImmutableMap.of(
        "css", MediaType.CSS_UTF_8.withoutParameters(),
        "html", MediaType.HTML_UTF_8.withoutParameters(),
        "js", MediaType.JAVASCRIPT_UTF_8.withoutParameters());

    private static final String STATIC_RESOURCE_BASE_PATH = "/static/resource/";
    private static final String HUB_HTML_PATH = STATIC_RESOURCE_BASE_PATH + "hub.html";

    public boolean isStaticResourceRequest(HttpServletRequest request) {
      return "GET".equalsIgnoreCase(request.getMethod())
             && nullToEmpty(request.getPathInfo()).startsWith(STATIC_RESOURCE_BASE_PATH);
    }

    public void redirectToHub(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
      response.sendRedirect(request.getContextPath() + request.getServletPath() + HUB_HTML_PATH);
    }

    public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
      checkArgument(isStaticResourceRequest(request));

      String path = String.format(
          "/%s/%s",
          StaticResourceHandler.class.getPackage().getName().replace(".", "/"),
          request.getPathInfo().substring(STATIC_RESOURCE_BASE_PATH.length()));
      URL url = StaticResourceHandler.class.getResource(path);

      if (url == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }

      response.setStatus(HttpServletResponse.SC_OK);

      String extension = Files.getFileExtension(path);
      if (MIME_TYPES.containsKey(extension)) {
        response.setContentType(MIME_TYPES.get(extension).toString());
      }

      byte[] data = getResourceData(url);
      response.setContentLength(data.length);

      OutputStream output = response.getOutputStream();
      output.write(data);
      output.flush();
      output.close();
    }

    private byte[] getResourceData(URL url) throws IOException {
      InputStream stream = null;
      try {
        stream = url.openStream();
        return ByteStreams.toByteArray(stream);
      } finally {
        if (stream != null) {
          stream.close();
        }
      }
    }
  }
}


text:
myControllerModule.controller('NodesController', function(alertService,
$scope, NodesFactory, $state, $uibModal, displayRestError, CommonServices, mchelper, $filter) {

  //GUI page settings
  $scope.headerStringList = $filter('translate')('NODES_DETAIL');
  $scope.noItemsSystemMsg = $filter('translate')('NO_NODES_SETUP');
  $scope.noItemsSystemIcon = "fa fa-sitemap";

  //load empty, configuration, etc.,
  $scope.mchelper = mchelper;
  $scope.filteredList=[];

  //data query details
  $scope.currentPage = 1;
  $scope.query = CommonServices.getQuery();
  $scope.queryResponse = {};

  //Get min number
  $scope.getMin = function(item1, item2){
    return CommonServices.getMin(item1, item2);
  };

  //get all Nodes
  $scope.getAllItems = function(){
    NodesFactory.getAll($scope.query, function(response) {
      $scope.queryResponse = response;
      $scope.filteredList = $scope.queryResponse.data;
      $scope.filterConfig.resultsCount = $scope.queryResponse.query.filteredCount;
    },function(error){
      displayRestError.display(error);
    });
  }

  //Hold all the selected item ids
  $scope.itemIds = [];

  $scope.selectAllItems = function(){
    CommonServices.selectAllItems($scope);
  };

  $scope.selectItem = function(item){
    CommonServices.selectItem($scope, item);
  };

  //On page change
  $scope.pageChanged = function(newPage){
    CommonServices.updatePageChange($scope, newPage);
  };

  //Filter change method
  var filterChange = function (filters) {
    //Reset filter fields and update items
    CommonServices.updateFiltersChange($scope, filters);
  };

  $scope.filterConfig = {
    fields: [
      {
        id: 'name',
        title: $filter('translate')('NAME'),
        placeholder: $filter('translate')('FILTER_BY_NAME'),
        filterType: 'text'
      },
      {
        id: 'state',
        title:  $filter('translate')('STATUS'),
        placeholder: $filter('translate')('FILTER_BY_STATUS'),
        filterType: 'select',
        filterValues: ['Up','Down','Unavailable'],
      },
      {
        id: 'type',
        title:  'Type',
        placeholder: $filter('translate')('FILTER_BY_TYPE'),
        filterType: 'select',
        filterValues: ['Node','Repeater node'],
      },
      {
        id: 'eui',
        title:  'EUI',
        placeholder: $filter('translate')('FILTER_BY_EUI'),
        filterType: 'text',
      },
      {
        id: 'version',
        title:  'Version',
        placeholder: $filter('translate')('FILTER_BY_VERSION'),
        filterType: 'text',
      },
      {
        id: 'libVersion',
        title:  'Library Version',
        placeholder: $filter('translate')('FILTER_BY_LIBRARY_VERSION'),
        filterType: 'text',
      }
    ],
    resultsCount: $scope.filteredList.length,
    appliedFilters: [],
    onFilterChange: filterChange
    };

  //Sort columns
  var sortChange = function (sortId, isAscending) {
    //Reset sort type and update items
    CommonServices.updateSortChange($scope, sortId, isAscending);
  };

  $scope.sortConfig = {
    fields: [
      {
        id: 'name',
        title:  $filter('translate')('NAME'),
        sortType: 'text'
      },
      {
        id: 'state',
        title:  $filter('translate')('STATUS'),
        sortType: 'text'
      },
      {
        id: 'eui',
        title:  $filter('translate')('EUI'),
        sortType: 'text'
      },
      {
        id: 'type',
        title:  $filter('translate')('TYPE'),
        sortType: 'text'
      },
      {
        id: 'version',
        title:  $filter('translate')('VERSION'),
        sortType: 'text'
      },
      {
        id: 'libVersion',
        title:  $filter('translate')('LIBRARY_VERSION'),
        sortType: 'text'
      }
    ],
    onSortChange: sortChange
  };

  //Delete Node(s)
  $scope.delete = function (size) {
    var modalInstance = $uibModal.open({
    templateUrl: 'partials/common-html/delete-modal.html',
    controller: 'ControllerDeleteModal',
    size: size,
    resolve: {}
    });

    modalInstance.result.then(function () {
      NodesFactory.deleteIds($scope.itemIds, function(response) {
        alertService.success($filter('translate')('ITEMS_DELETED_SUCCESSFULLY'));
        //Update display table
        $scope.getAllItems();
        $scope.itemIds = [];
      },function(error){
        displayRestError.display(error);
      });
    }),
    function () {
      //console.log('Modal dismissed at: ' + new Date());
    }
  };

  //Edit item
  $scope.edit = function () {
    if($scope.itemIds.length == 1){
      $state.go("nodesAddEdit",{'id':$scope.itemIds[0]});
    }
  };

  //Upload Firmware
  $scope.uploadFirmware = function (size) {
    if($scope.itemIds.length > 0){
      NodesFactory.uploadFirmware($scope.itemIds,function(response) {
        alertService.success($filter('translate')('FIRMWARE_UPLOAD_INITIATED'));
      },function(error){
        displayRestError.display(error);
      });
    }
  };

  //Reboot a Node
  $scope.reboot = function (size) {
    var addModalInstance = $uibModal.open({
    templateUrl: 'partials/nodes/node-reboot-modal.html',
    controller: 'NodesControllerReboot',
    size: size,
    resolve: {}
    });

    addModalInstance.result.then(function () {
      NodesFactory.reboot($scope.itemIds, function(response) {
        alertService.success($filter('translate')('REBOOT_INITIATED'));
      },function(error){
        displayRestError.display(error);
      });
    }),
    function () {
      //console.log('Modal dismissed at: ' + new Date());
    }
  };

  //Erase Configuration of Nodes
  $scope.eraseConfiguration = function (size) {
    var addModalInstance = $uibModal.open({
    templateUrl: 'partials/nodes/node-erase-configuration-modal.html',
    controller: 'NodesControllerEraseConfiguration',
    size: size,
    resolve: {}
    });

    addModalInstance.result.then(function () {
      NodesFactory.eraseConfiguration($scope.itemIds, function(response) {
        alertService.success($filter('translate')('ERASE_CONFIGURATION_INITIATED'));
      },function(error){
        displayRestError.display(error);
      });
    }),
    function () {
      //console.log('Modal dismissed at: ' + new Date());
    }
  };

});

// Nodes other controllers

//Add/Edit Node
myControllerModule.controller('NodesControllerAddEdit', function ($scope, $stateParams, GatewaysFactory, NodesFactory, TypesFactory, mchelper, alertService, displayRestError, $filter, $state) {
  //Load mchelper variables to this scope
  $scope.mchelper = mchelper;
  $scope.node = {};
  if($stateParams.id){
    $scope.node = NodesFactory.get({"nodeId":$stateParams.id});
  }
  $scope.node.gateway = {};
  $scope.gateways = TypesFactory.getGateways();
  $scope.nodeTypes = TypesFactory.getNodeTypes();
  $scope.firmwares = TypesFactory.getFirmwares();

  //GUI page settings
  $scope.showHeaderUpdate = $stateParams.id;
  $scope.headerStringAdd = $filter('translate')('ADD_NODE');
  $scope.headerStringUpdate = $filter('translate')('UPDATE_NODE');
  $scope.cancelButtonState = "nodesList"; //Cancel button state
  $scope.saveProgress = false;
  //$scope.isSettingChange = false;

  $scope.save = function(){
      $scope.saveProgress = true;
    if($stateParams.id){
      NodesFactory.update($scope.node,function(response) {
        alertService.success($filter('translate')('ITEM_UPDATED_SUCCESSFULLY'));
        $state.go("nodesList");
      },function(error){
        displayRestError.display(error);
        $scope.saveProgress = false;
      });
    }else{
      NodesFactory.create($scope.node,function(response) {
        alertService.success($filter('translate')('ITEM_CREATED_SUCCESSFULLY'));
        $state.go("nodesList");
      },function(error){
        displayRestError.display(error);
        $scope.saveProgress = false;
      });
    }
  }
});

//Node Detail
myControllerModule.controller('NodesControllerDetail', function ($scope, $stateParams, mchelper, NodesFactory, TypesFactory, MetricsFactory, $filter, $timeout, $window) {
  //Load mchelper variables to this scope
  $scope.mchelper = mchelper;
  $scope.item = {};
  $scope.headerStringList = $filter('translate')('NODE_DETAILS');

  $scope.item = NodesFactory.get({"nodeId":$stateParams.id});
  $scope.resourceCount = MetricsFactory.getResourceCount({"resourceType":"NODE", "resourceId":$stateParams.id});

  $scope.chartOptions = {
        chart: {
            type: 'lineChart',
            noErrorCheck: true,
            height: 325,
            width:null,
            margin : {
                top: 0,
                right: 10,
                bottom: 90,
                left: 65
            },
            color: ["#2ca02c","#1f77b4", "#ff7f0e"],

            x: function(d){return d[0];},
            y: function(d){return d[1];},
            useVoronoi: false,
            clipEdge: false,
            transitionDuration: 500,
            useInteractiveGuideline: true,
            xAxis: {
                showMaxMin: false,
                tickFormat: function(d) {
                    return d3.time.format('hh:mm:ss a')(new Date(d))
                },
                //axisLabel: 'Timestamp',
                rotateLabels: -20
            },
            yAxis: {
                tickFormat: function(d){
                    return d3.format(',.2f')(d) + ' %';
                },
                //axisLabel: ''
            }
        },
          title: {
            enable: false,
            text: 'Title'
        }
    };

  //pre select, should be updated from server
  TypesFactory.getMetricsSettings(function(response){
    $scope.metricsSettings = response;
    $scope.chartEnableMinMax = $scope.metricsSettings.enabledMinMax;
    $scope.chartFromTimestamp = $scope.metricsSettings.defaultTimeRange.toString();
    MetricsFactory.getBatteryMetrics({"nodeId":$stateParams.id, "withMinMax":$scope.chartEnableMinMax, "timestampFrom": new Date().getTime() - $scope.chartFromTimestamp},function(response){
      $scope.batteryChartData = response;
      //Update display time format
      $scope.chartTimeFormat = response.timeFormat;
      $scope.chartOptions.chart.type = response.chartType;
      $scope.chartOptions.chart.interpolate = response.chartInterpolate;
      $scope.fetching = false;
    });
  });
  $scope.chartTimeFormat = mchelper.cfg.dateFormat;
  $scope.chartOptions.chart.xAxis.tickFormat = function(d) {return $filter('date')(d, $scope.chartTimeFormat, mchelper.cfg.timezone)};

  $scope.updateChart = function(){
    MetricsFactory.getBatteryMetrics({"nodeId":$stateParams.id, "withMinMax":$scope.chartEnableMinMax, "timestampFrom": new Date().getTime() - $scope.chartFromTimestamp}, function(resource){
      $scope.batteryChartData.chartData = resource.chartData;
      //Update display time format
      $scope.chartTimeFormat = resource.timeFormat;
    });
  }

  //Graph resize issue, see: https://github.com/krispo/angular-nvd3/issues/40
  $scope.$watch('fetching', function() {
      if(!$scope.fetching) {
        $timeout(function() {
          $window.dispatchEvent(new Event('resize'));
          $scope.fetching = true;
        }, 1000);
      }
    });

});

//Erase Configuration Modal
myControllerModule.controller('NodesControllerEraseConfiguration', function ($scope, $uibModalInstance, $filter) {
  $scope.header = $filter('translate')('ERASE_CONFIGURATION_CONFIRMATION_TITLE');
  $scope.eraseMsg = $filter('translate')('ERASE_CONFIGURATION_CONFIRMATION_MESSAGE');
  $scope.eraseNodeConfiguration = function() {$uibModalInstance.close(); };
  $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});

//reboot Modal
myControllerModule.controller('NodesControllerReboot', function ($scope, $uibModalInstance, $filter) {
  $scope.header = $filter('translate')('REBOOT_CONFIRMATION_TITLE');
  $scope.rebootMsg = $filter('translate')('REBOOT_CONFIRMATION_MESSAGE');
  $scope.reboot = function() {$uibModalInstance.close(); };
  $scope.cancel = function () { $uibModalInstance.dismiss('cancel'); }
});

redpajama_set_name: RedPajamaGithub


text:
package org.nextime.ion.backoffice.action.content;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.nextime.ion.backoffice.action.BaseAction;
import org.nextime.ion.backoffice.exception.BackofficeSecurityException;
import org.nextime.ion.backoffice.security.SecurityManagerImpl;
import org.nextime.ion.commons.PublicationSorter;
import org.nextime.ion.framework.business.Publication;
import org.nextime.ion.framework.business.Section;
import org.nextime.ion.framework.business.User;
import org.nextime.ion.framework.mapping.Mapping;

public class DeletePublicationAction extends BaseAction {

    public ActionForward perform(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        // check if user is correctly logged
        checkUser(request);

        // retrieve selected publication
        String selectedId = request.getParameter("id");

        // check if this action is allowed
        try {
            Mapping.begin();
            if (!new SecurityManagerImpl().canDeletePublication(Publication.getInstance(selectedId), User.getInstance(request.getSession().getAttribute("userLogin") + ""))) {
                throw new Exception();
            }
        } catch (Exception e) {
            throw new BackofficeSecurityException();
        } finally {
            Mapping.rollback();
        }

        try {
            Mapping.begin();

            Publication publication = Publication.getInstance(selectedId);
            Section section = Section.getInstance(request.getParameter("sectionId"));
            PublicationSorter.removePublication(publication, section);
            publication.remove();

            Mapping.commit();
        } catch (Exception e) {
            Mapping.rollback();
            throw new ServletException(e);
        }

        // Forward to the next page
        return (mapping.findForward("ok"));

    }

}


text:
package com.microsoft;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import com.microsoft.aad.adal.ADALError;
import com.microsoft.aad.adal.AuthenticationCallback;
import com.microsoft.aad.adal.AuthenticationContext;
import com.microsoft.aad.adal.AuthenticationException;
import com.microsoft.aad.adal.AuthenticationResult;
import com.microsoft.aad.adal.PromptBehavior;

import static com.microsoft.aad.adal.AuthenticationResult.AuthenticationStatus.Succeeded;

public class AuthenticationManager {

    private static final String USER_ID_VAR_NAME = "userId";

    private static final int PREFERENCES_MODE = Context.MODE_PRIVATE;

    private final Activity mActivity;

    private final AuthenticationContext mAuthenticationContext;

    private final String
            mAuthenticationResourceId,
            mSharedPreferencesFilename,
            mClientId,
            mRedirectUri;

    AuthenticationManager(
            Activity activity,
            AuthenticationContext authenticationContext,
            String authenticationResourceId,
            String sharedPreferencesFilename,
            String clientId,
            String redirectUri) {
        mActivity = activity;
        mAuthenticationContext = authenticationContext;
        mAuthenticationResourceId = authenticationResourceId;
        mSharedPreferencesFilename = sharedPreferencesFilename;
        mClientId = clientId;
        mRedirectUri = redirectUri;
    }

    private SharedPreferences getSharedPreferences() {
        return mActivity.getSharedPreferences(mSharedPreferencesFilename, PREFERENCES_MODE);
    }

    public void connect(AuthenticationCallback<AuthenticationResult> authenticationCallback) {
        if (isConnected()) {
            authenticateSilent(authenticationCallback);
        } else {
            authenticatePrompt(authenticationCallback);
        }
    }

    /**
     * Disconnects the app from Office 365 by clearing the token cache, setting the client objects
     * to null, and removing the user id from shred preferences.
     */
    public void disconnect() {
        // Clear tokens.
        if (mAuthenticationContext.getCache() != null) {
            mAuthenticationContext.getCache().removeAll();
        }

        // Forget the user
        removeUserId();
    }

    private void authenticatePrompt(
            final AuthenticationCallback<AuthenticationResult> authenticationCallback) {
        mAuthenticationContext
                .acquireToken(
                        mAuthenticationResourceId,
                        mClientId,
                        mRedirectUri,
                        null,
                        PromptBehavior.Always,
                        null,
                        new AuthenticationCallback<AuthenticationResult>() {
                            @Override
                            public void onSuccess(final AuthenticationResult authenticationResult) {
                                if (Succeeded == authenticationResult.getStatus()) {
                                    setUserId(authenticationResult.getUserInfo().getUserId());
                                    authenticationCallback.onSuccess(authenticationResult);
                                } else {
                                    onError(
                                            new AuthenticationException(ADALError.AUTH_FAILED,
                                                    authenticationResult.getErrorCode()));
                                }
                            }

                            @Override
                            public void onError(Exception e) {
                                disconnect();
                                authenticationCallback.onError(e);
                            }
                        }
                );
    }

    private void authenticateSilent(
            final AuthenticationCallback<AuthenticationResult> authenticationCallback) {
        mAuthenticationContext.acquireTokenSilent(
                mAuthenticationResourceId,
                mClientId,
                getUserId(),
                new AuthenticationCallback<AuthenticationResult>() {
                    @Override
                    public void onSuccess(AuthenticationResult authenticationResult) {
                        authenticationCallback.onSuccess(authenticationResult);
                    }

                    @Override
                    public void onError(Exception e) {
                        authenticatePrompt(authenticationCallback);
                    }
                });
    }

    private boolean isConnected() {
        return getSharedPreferences().contains(USER_ID_VAR_NAME);
    }

    private String getUserId() {
        return getSharedPreferences().getString(USER_ID_VAR_NAME, "");
    }

    private void setUserId(String value) {
        SharedPreferences.Editor editor = getSharedPreferences().edit();
        editor.putString(USER_ID_VAR_NAME, value);
        editor.apply();
    }

    private void removeUserId() {
        SharedPreferences.Editor editor = getSharedPreferences().edit();
        editor.remove(USER_ID_VAR_NAME);
        editor.apply();
    }

}
// *********************************************************
//
// O365-Android-ArtCurator https://github.com/OfficeDev/O365-Android-ArtCurator
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// 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.
//
// *********************************************************


text:
//
//  DBValidationStringLengthRule.h
//  DBValidator
//

#import "DBValidationRule.h"

@interface DBValidationStringLengthRule : DBValidationRule

-(id) initWithObject:(id)object keyPath:(NSString *)keyPath minStringLength: (NSUInteger) minLength maxStringLength: (NSUInteger) maxLength failureMessage:(NSString *)failureMessage;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/songQuery"
        android:layout_width="fill_parent"
        android:layout_height="70dp"
        android:layout_gravity="center_horizontal"
        android:layout_centerHorizontal="true"
        android:hint="@string/chooseSong"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:singleLine="true"
        />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="5"
        android:drawSelectorOnTop="false"
        />

</LinearLayout>