Example #1
0
  /** Costructs a new Jukebox. */
  public Jukebox(SipProvider sip_provider, UserAgentProfile user_profile) {
    log = sip_provider.getLog();
    this.user_profile = user_profile;
    this.sip_provider = sip_provider;

    if (user_profile.contact_url == null)
      user_profile.contact_url =
          user_profile.username + "@" + sip_provider.getViaAddress() + ":" + sip_provider.getPort();

    if (!user_profile.no_prompt) stdout = System.out;

    if (user_profile.do_register) {
      RegisterAgent ra =
          new RegisterAgent(
              sip_provider,
              user_profile.from_url,
              user_profile.contact_url,
              user_profile.username,
              user_profile.username,
              user_profile.realm,
              user_profile.passwd,
              this);
      ra.loopRegister(user_profile.expires, user_profile.expires / 2);
    }

    UserAgent ua = new UserAgent(sip_provider, user_profile, this);
    ua.listen();
  }
    public static UserAgent find(String uaString) {
      for (UserAgent agent : values()) {
        if (agent.toString().equalsIgnoreCase(uaString)) {
          return agent;
        }
      }

      return null;
    }
Example #3
0
  /** Receives incoming calls (auto accept) */
  public void listen() {
    for (UserAgent ua : uas) {
      if (ua != null) {
        ua.printLog("UAS: WAITING FOR INCOMING CALL");

        if (!ua.user_profile.audio && !ua.user_profile.video) {
          ua.printLog("ONLY SIGNALING, NO MEDIA");
        }

        ua.listen();
      }
    }
  }
Example #4
0
  /** When a new call is incoming */
  public void onUaCallIncoming(
      UserAgent ua, SessionDescriptor remote_sdp, NameAddress callee, NameAddress caller) {
    printOut("Incoming Call from " + caller.toString());

    String audio_file = callee.getAddress().getParameter(PARAM_RESOURCE);
    if (audio_file != null) if (new File(audio_file).isFile()) user_profile.send_file = audio_file;

    if (user_profile.send_file != null) ua.accept();
    else ua.hangup();

    user_profile.audio_port++;
    ua = new UserAgent(sip_provider, user_profile, this);
    ua.listen();
  }
Example #5
0
  public static void main(final String[] args) throws AuthorizationException, URISyntaxException {

    final URI authorizationEndpoint = new URI(args[0]);
    final URI redirectUri = new URI(args[1]);

    final UserAgent userAgent = new UserAgentImpl();

    final AuthorizationResponse authorizationResponse =
        userAgent.requestAuthorizationCode(authorizationEndpoint, redirectUri);

    code = authorizationResponse.getCode();
    state = authorizationResponse.getState();
    System.out.print("Authorization Code: ");
    System.out.println(code);
  }
Example #6
0
  public void unregister() throws SipUriSyntaxException {
    if (getInitialRequestManager().getRegisterHandler().isRegistered()) {
      String requestUri = RFC3261.SIP_SCHEME + RFC3261.SCHEME_SEPARATOR + userAgent.getDomain();
      MessageInterceptor messageInterceptor =
          new MessageInterceptor() {

            @Override
            public void postProcess(SipMessage sipMessage) {
              initialRequestManager.registerHandler.unregister();
              SipHeaders sipHeaders = sipMessage.getSipHeaders();
              SipHeaderFieldValue contact =
                  sipHeaders.get(new SipHeaderFieldName(RFC3261.HDR_CONTACT));
              contact.addParam(new SipHeaderParamName(RFC3261.PARAM_EXPIRES), "0");
            }
          };
      initialRequestManager.createInitialRequest(
          requestUri,
          RFC3261.METHOD_REGISTER,
          profileUri,
          registerCallID,
          null,
          messageInterceptor);
      // initialRequestManager.registerHandler.unregister();
    }
  }
Example #7
0
 public void togglemute() {
   if (ua.muteMediaApplication())
     Receiver.onText(
         Receiver.CALL_NOTIFICATION,
         getUIContext().getString(R.string.menu_mute),
         android.R.drawable.stat_notify_call_mute,
         Receiver.ccCall.base);
   else Receiver.progress();
 }
  /**
   * 根据设置的参数构造相应的 {@code Fetcher} 对象。<br>
   * 构造完成后,将会重置该 {@code FetcherBuilder}。<br>
   * 如果参数未设置或设置不全将会抛出 {@code IllegalStateException} 异常。
   *
   * @return {@code Fetcher} 对象
   * @throws IOException 构造失败
   */
  public Fetcher build() throws IOException {
    try {
      requireNonNull(site, "The parameter 'site' haven't been set yet.");
      requireNonNull(page, "The parameter 'page' haven't been set yet.");
    } catch (NullPointerException e) {
      throw new IllegalStateException(e);
    }

    if (isNullOrEmpty(userAgent)) userAgent = UserAgent.getUserAgent();

    if (site.equals("*")) site = matchSiteFromPage(page);

    Fetcher fetcher;

    switch (site) {
      case "uta-net.com":
        fetcher = new UtaNetFetcher(page, userAgent);
        break;
      case "j-lyric.net":
        fetcher = new JLyricFetcher(page, userAgent);
        break;
      case "utamap.com":
        fetcher = new UtaMapFetcher(page, userAgent);
        break;
      case "kasi-time.com":
        fetcher = new KasiTimeFetcher(page, userAgent);
        break;
      case "kashinavi.com":
        fetcher = new KashiNaviFetcher(page, userAgent);
        break;
      case "kget.jp":
        fetcher = new KGetFetcher(page, userAgent);
        break;
      case "utaten.com":
        fetcher = new UtaTenFetcher(page, userAgent);
        break;
      case "animap.jp":
        fetcher = new AniMapFetcher(page, userAgent);
        break;
      case "evesta.jp":
        fetcher = new EvestaFetcher(page, userAgent);
        break;
      case "jtw.zaq.ne.jp/animesong":
        fetcher = new AnimeSongFetcher(page, userAgent);
        break;
      case "joysound.com":
        fetcher = new JoySoundFetcher(page, userAgent);
        break;
      case "petitlyrics.com":
        fetcher = new PetitLyricsFetcher(page, userAgent);
        break;
      default:
        throw new IllegalArgumentException("Unable to resolve the parameter 'site': " + site);
    }

    return fetcher;
  }
Example #9
0
 /**
  * For the moment we consider that only one profile uri is used at a time.
  *
  * @throws SipUriSyntaxException
  */
 public SipRequest register() throws SipUriSyntaxException {
   String domain = userAgent.getDomain();
   String requestUri = RFC3261.SIP_SCHEME + RFC3261.SCHEME_SEPARATOR + domain;
   SipListener sipListener = userAgent.getSipListener();
   profileUri =
       RFC3261.SIP_SCHEME
           + RFC3261.SCHEME_SEPARATOR
           + userAgent.getUserpart()
           + RFC3261.AT
           + domain;
   registerCallID = Utils.generateCallID(userAgent.getConfig().getLocalInetAddress());
   SipRequest sipRequest =
       initialRequestManager.createInitialRequest(
           requestUri, RFC3261.METHOD_REGISTER, profileUri, registerCallID);
   if (sipListener != null) {
     sipListener.registering(sipRequest);
   }
   return sipRequest;
 }
Example #10
0
  /** Makes a new call */
  public boolean call(String target_url, boolean force) {
    int p = pref;
    boolean found = false;

    if (isRegistered(p) && Receiver.isFast(p)) found = true;
    else {
      for (p = 0; p < LINES; p++)
        if (isRegistered(p) && Receiver.isFast(p)) {
          found = true;
          break;
        }
      if (!found && force) {
        p = pref;
        if (Receiver.isFast(p)) found = true;
        else
          for (p = 0; p < LINES; p++)
            if (Receiver.isFast(p)) {
              found = true;
              break;
            }
      }
    }

    if (!found || (ua = uas[p]) == null) {
      if (PreferenceManager.getDefaultSharedPreferences(getUIContext())
              .getBoolean(Settings.PREF_CALLBACK, Settings.DEFAULT_CALLBACK)
          && PreferenceManager.getDefaultSharedPreferences(getUIContext())
                  .getString(Settings.PREF_POSURL, Settings.DEFAULT_POSURL)
                  .length()
              > 0) {
        Receiver.url("n=" + Uri.decode(target_url));
        return true;
      }
      return false;
    }

    ua.printLog("UAC: CALLING " + target_url);

    if (!ua.user_profile.audio && !ua.user_profile.video) {
      ua.printLog("ONLY SIGNALING, NO MEDIA");
    }
    return ua.call(target_url, false);
  }
 public static EmulationProfile fromJson(JSONObject json) throws JSONException {
   return builder()
       .setProfileName(String.valueOf(json.get("profileName")))
       .setWidth(Integer.parseInt(String.valueOf(json.get("width"))))
       .setHeight(Integer.parseInt(String.valueOf(json.get("height"))))
       .setPPI(Integer.parseInt(String.valueOf(json.get("ppi"))))
       .setIME(IME.valueOf(String.valueOf(json.get("ime")).toUpperCase()))
       .setUserAgent(UserAgent.find(String.valueOf(json.get("userAgent"))))
       .build();
 }
Example #12
0
  public static void main(String[] args) {
    try {
      UserAgent userAgent = new UserAgent();
      userAgent.visit("http://jaunt-api.com/examples/food.htm");

      Elements elements = userAgent.doc.findEvery("<div>"); // find all divs in the document
      System.out.println(
          "Every div: " + elements.size() + " results"); // report number of search results.

      elements = userAgent.doc.findEach("<div>"); // find all non-nested divs
      System.out.println(
          "Each div: " + elements.size() + " results"); // report number of search results.
      // find non-nested divs within <p class='meat'>
      elements = userAgent.doc.findFirst("<p class=meat>").findEach("<div>");
      System.out.println(
          "Meat search: " + elements.size() + " results"); // report number of search results.
    } catch (JauntException e) {
      System.out.println(e);
    }
  }
Example #13
0
  public static void main(String[] args) {
    try {
      UserAgent userAgent = new UserAgent();
      userAgent.visit("http://jaunt-api.com/examples/signup.htm");
      Document doc = userAgent.doc;

      doc.fillout(
          "E-mail:", "*****@*****.**"); // fill out the (textfield) component labelled "E-mail:"
      doc.choose(
          "Account Type:", "advanced"); // choose "advanced" from the menu labelled "Account Type:"
      doc.fillout(
          "Comments:", "no comment"); // fill out the (textarea) component labelled "Comments:"
      doc.choose(
          Label.RIGHT,
          "No thanks"); // choose the (radiobutton) component right-labelled "No thanks"
      doc.submit("create trial account"); // press the submit button labelled 'create trial account'
      System.out.println(userAgent.getLocation()); // print the current location (url)
    } catch (JauntException e) {
      System.out.println(e);
    }
  }
Example #14
0
 /** should be instanciated only once, it was a singleton. */
 public UAC(
     UserAgent userAgent,
     InitialRequestManager initialRequestManager,
     MidDialogRequestManager midDialogRequestManager,
     DialogManager dialogManager,
     TransactionManager transactionManager,
     TransportManager transportManager,
     Logger logger) {
   this.userAgent = userAgent;
   this.initialRequestManager = initialRequestManager;
   this.midDialogRequestManager = midDialogRequestManager;
   this.dialogManager = dialogManager;
   this.transactionManager = transactionManager;
   this.logger = logger;
   guiClosedCallIds = Collections.synchronizedList(new ArrayList<String>());
   profileUri =
       RFC3261.SIP_SCHEME
           + RFC3261.SCHEME_SEPARATOR
           + userAgent.getUserpart()
           + RFC3261.AT
           + userAgent.getDomain();
 }
Example #15
0
  public static void main(String[] args) {
    try {
      UserAgent userAgent = new UserAgent();
      userAgent.visit("http://jaunt-api.com/examples/hello.htm");

      Elements elements =
          userAgent.doc.findEvery("<div|span>"); // find every element who's tagname is div or span.
      System.out.println("search results:\n" + elements.innerHTML()); // print the search results

      elements = userAgent.doc.findEvery("<p id=1|4>"); // find every p element who's id is 1 or 4
      System.out.println("search results:\n" + elements.innerHTML()); // print the search results

      elements =
          userAgent.doc.findEvery("< id=[2-6]>"); // find every element (any name) with id from 2-6
      System.out.println("search results:\n" + elements.innerHTML()); // print the search results

      elements =
          userAgent.doc.findEvery(
              "&lt;p>ho"); // find every p who's joined child text contains 'ho' (regex)
      System.out.println("search results:\n" + elements.innerHTML()); // print the search results
    } catch (ResponseException e) {
      System.out.println(e);
    }
  }
Example #16
0
 public void info(char c, int duration) {
   ua.info(c, duration);
 }
 public String getUserAgent() {
   return userAgent.toString();
 }
Example #18
0
  /** Tries to build a GVTFontFamily from a URL reference */
  protected GVTFontFamily getFontFamily(BridgeContext ctx, ParsedURL purl) {
    String purlStr = purl.toString();

    Element e = getBaseElement(ctx);
    SVGDocument svgDoc = (SVGDocument) e.getOwnerDocument();
    String docURL = svgDoc.getURL();
    ParsedURL pDocURL = null;
    if (docURL != null) pDocURL = new ParsedURL(docURL);

    // try to load an SVG document
    String baseURI = AbstractNode.getBaseURI(e);
    purl = new ParsedURL(baseURI, purlStr);
    UserAgent userAgent = ctx.getUserAgent();

    try {
      userAgent.checkLoadExternalResource(purl, pDocURL);
    } catch (SecurityException ex) {
      // Can't load font - Security violation.
      // We should not throw the error that is for certain, just
      // move down the font list, but do we display the error or not???
      // I'll vote yes just because it is a security exception (other
      // exceptions like font not available etc I would skip).
      userAgent.displayError(ex);
      return null;
    }

    if (purl.getRef() != null) {
      // Reference must be to a SVGFont.
      Element ref = ctx.getReferencedElement(e, purlStr);
      if (!ref.getNamespaceURI().equals(SVG_NAMESPACE_URI)
          || !ref.getLocalName().equals(SVG_FONT_TAG)) {
        return null;
      }

      SVGDocument doc = (SVGDocument) e.getOwnerDocument();
      SVGDocument rdoc = (SVGDocument) ref.getOwnerDocument();

      Element fontElt = ref;
      if (doc != rdoc) {
        fontElt = (Element) doc.importNode(ref, true);
        String base = AbstractNode.getBaseURI(ref);
        Element g = doc.createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
        g.appendChild(fontElt);
        g.setAttributeNS(XMLConstants.XML_NAMESPACE_URI, "xml:base", base);
        CSSUtilities.computeStyleAndURIs(ref, fontElt, purlStr);
      }

      // Search for a font-face element
      Element fontFaceElt = null;
      for (Node n = fontElt.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ((n.getNodeType() == Node.ELEMENT_NODE)
            && n.getNamespaceURI().equals(SVG_NAMESPACE_URI)
            && n.getLocalName().equals(SVG_FONT_FACE_TAG)) {
          fontFaceElt = (Element) n;
          break;
        }
      }
      // todo : if the above loop fails to find a fontFaceElt, a null is passed to createFontFace()

      SVGFontFaceElementBridge fontFaceBridge;
      fontFaceBridge =
          (SVGFontFaceElementBridge) ctx.getBridge(SVG_NAMESPACE_URI, SVG_FONT_FACE_TAG);
      GVTFontFace gff = fontFaceBridge.createFontFace(ctx, fontFaceElt);

      return new SVGFontFamily(gff, fontElt, ctx);
    }
    // Must be a reference to a 'Web Font'.
    try {
      return ctx.getFontFamilyResolver().loadFont(purl.openStream(), this);
    } catch (Exception ex) {
    }
    return null;
  }
Example #19
0
 public int speaker(int mode) {
   int ret = ua.speakerMediaApplication(mode);
   Receiver.progress();
   return ret;
 }
Example #20
0
 public void terminate(SipRequest sipRequest) {
   String callId = Utils.getMessageCallId(sipRequest);
   if (!guiClosedCallIds.contains(callId)) {
     guiClosedCallIds.add(callId);
   }
   Dialog dialog = dialogManager.getDialog(callId);
   SipRequest inviteWithAuth = getInviteWithAuth(callId);
   if (dialog != null) {
     SipRequest originatingRequest;
     if (inviteWithAuth != null) {
       originatingRequest = inviteWithAuth;
     } else {
       originatingRequest = sipRequest;
     }
     ClientTransaction clientTransaction =
         transactionManager.getClientTransaction(originatingRequest);
     if (clientTransaction != null) {
       synchronized (clientTransaction) {
         DialogState dialogState = dialog.getState();
         if (dialog.EARLY.equals(dialogState)) {
           initialRequestManager.createCancel(inviteWithAuth, midDialogRequestManager, profileUri);
         } else if (dialog.CONFIRMED.equals(dialogState)) {
           // clientTransaction not yet removed
           midDialogRequestManager.generateMidDialogRequest(dialog, RFC3261.METHOD_BYE, null);
           guiClosedCallIds.remove(callId);
         }
       }
     } else {
       // clientTransaction Terminated and removed
       logger.debug("clientTransaction null");
       midDialogRequestManager.generateMidDialogRequest(dialog, RFC3261.METHOD_BYE, null);
       guiClosedCallIds.remove(callId);
     }
   } else {
     InviteClientTransaction inviteClientTransaction =
         (InviteClientTransaction) transactionManager.getClientTransaction(inviteWithAuth);
     if (inviteClientTransaction == null) {
       logger.error("cannot find invite client transaction" + " for call " + callId);
     } else {
       SipResponse sipResponse = inviteClientTransaction.getLastResponse();
       if (sipResponse != null) {
         int statusCode = sipResponse.getStatusCode();
         if (statusCode < RFC3261.CODE_200_OK) {
           initialRequestManager.createCancel(inviteWithAuth, midDialogRequestManager, profileUri);
         }
       }
     }
   }
   switch (userAgent.getMediaMode()) {
     case captureAndPlayback:
       userAgent.getMediaManager().stopSession();
       SoundManager soundManager = userAgent.getSoundManager();
       if (soundManager != null) {
         soundManager.closeLines();
       }
       break;
     case echo:
       Echo echo = userAgent.getEcho();
       if (echo != null) {
         echo.stop();
         userAgent.setEcho(null);
       }
       break;
     case file:
       MediaManager mediaManager = userAgent.getMediaManager();
       mediaManager.stopSession();
       break;
     default:
       break;
   }
 }
Example #21
0
 public void togglehold() {
   ua.reInvite(null, 0);
 }
Example #22
0
 public void answercall() {
   Receiver.stopRingtone();
   ua.accept();
 }
Example #23
0
 public void rejectcall() {
   ua.printLog("UA: HANGUP");
   ua.hangup();
 }
Example #24
0
  /** Loads the scripts contained in the <script> elements. */
  public void loadScripts() {
    org.apache.batik.script.Window window = null;

    NodeList scripts =
        document.getElementsByTagNameNS(
            SVGConstants.SVG_NAMESPACE_URI, SVGConstants.SVG_SCRIPT_TAG);
    int len = scripts.getLength();

    if (len == 0) {
      return;
    }

    for (int i = 0; i < len; i++) {
      AbstractElement script = (AbstractElement) scripts.item(i);
      String type = script.getAttributeNS(null, SVGConstants.SVG_TYPE_ATTRIBUTE);

      if (type.length() == 0) {
        type = SVGConstants.SVG_SCRIPT_TYPE_DEFAULT_VALUE;
      }

      //
      // Java code invocation.
      //
      if (type.equals(SVGConstants.SVG_SCRIPT_TYPE_JAVA)) {
        try {
          String href = XLinkSupport.getXLinkHref(script);
          ParsedURL purl = new ParsedURL(script.getBaseURI(), href);

          checkCompatibleScriptURL(type, purl);

          DocumentJarClassLoader cll;
          URL docURL = null;
          try {
            docURL = new URL(docPURL.toString());
          } catch (MalformedURLException mue) {
            /* nothing just let docURL be null */
          }
          cll = new DocumentJarClassLoader(new URL(purl.toString()), docURL);

          // Get the 'Script-Handler' entry in the manifest.
          URL url = cll.findResource("META-INF/MANIFEST.MF");
          if (url == null) {
            continue;
          }
          Manifest man = new Manifest(url.openStream());

          String sh;

          sh = man.getMainAttributes().getValue("Script-Handler");
          if (sh != null) {
            // Run the script handler.
            ScriptHandler h;
            h = (ScriptHandler) cll.loadClass(sh).newInstance();

            if (window == null) {
              window = createWindow();
            }

            h.run(document, window);
          }

          sh = man.getMainAttributes().getValue("SVG-Handler-Class");
          if (sh != null) {
            // Run the initializer
            EventListenerInitializer initializer;
            initializer = (EventListenerInitializer) cll.loadClass(sh).newInstance();

            if (window == null) {
              window = createWindow();
            }

            initializer.initializeEventListeners((SVGDocument) document);
          }
        } catch (Exception e) {
          if (userAgent != null) {
            userAgent.displayError(e);
          }
        }
        continue;
      }

      //
      // Scripting language invocation.
      //
      Interpreter interpreter = getInterpreter(type);
      if (interpreter == null)
        // Can't find interpreter so just skip this script block.
        continue;

      try {
        String href = XLinkSupport.getXLinkHref(script);
        String desc = null;
        Reader reader = null;

        if (href.length() > 0) {
          desc = href;

          // External script.
          ParsedURL purl = new ParsedURL(script.getBaseURI(), href);

          checkCompatibleScriptURL(type, purl);
          InputStream is = purl.openStream();
          String mediaType = purl.getContentTypeMediaType();
          String enc = purl.getContentTypeCharset();
          if (enc != null) {
            try {
              reader = new InputStreamReader(is, enc);
            } catch (UnsupportedEncodingException uee) {
              enc = null;
            }
          }
          if (reader == null) {
            if (APPLICATION_ECMASCRIPT.equals(mediaType)) {
              // No encoding was specified in the MIME type, so
              // infer it according to RFC 4329.
              if (purl.hasContentTypeParameter("version")) {
                // Future versions of application/ecmascript
                // are not supported, so skip this script
                // element if the version parameter is present.
                continue;
              }

              PushbackInputStream pbis = new PushbackInputStream(is, 8);
              byte[] buf = new byte[4];
              int read = pbis.read(buf);
              if (read > 0) {
                pbis.unread(buf, 0, read);
                if (read >= 2) {
                  if (buf[0] == (byte) 0xff && buf[1] == (byte) 0xfe) {
                    if (read >= 4 && buf[2] == 0 && buf[3] == 0) {
                      enc = "UTF32-LE";
                      pbis.skip(4);
                    } else {
                      enc = "UTF-16LE";
                      pbis.skip(2);
                    }
                  } else if (buf[0] == (byte) 0xfe && buf[1] == (byte) 0xff) {
                    enc = "UTF-16BE";
                    pbis.skip(2);
                  } else if (read >= 3
                      && buf[0] == (byte) 0xef
                      && buf[1] == (byte) 0xbb
                      && buf[2] == (byte) 0xbf) {
                    enc = "UTF-8";
                    pbis.skip(3);
                  } else if (read >= 4
                      && buf[0] == 0
                      && buf[1] == 0
                      && buf[2] == (byte) 0xfe
                      && buf[3] == (byte) 0xff) {
                    enc = "UTF-32BE";
                    pbis.skip(4);
                  }
                }
                if (enc == null) {
                  enc = "UTF-8";
                }
              }
              reader = new InputStreamReader(pbis, enc);
            } else {
              reader = new InputStreamReader(is);
            }
          }
        } else {
          checkCompatibleScriptURL(type, docPURL);
          DocumentLoader dl = bridgeContext.getDocumentLoader();
          Element e = script;
          SVGDocument d = (SVGDocument) e.getOwnerDocument();
          int line = dl.getLineNumber(script);
          desc =
              Messages.formatMessage(
                  INLINE_SCRIPT_DESCRIPTION,
                  new Object[] {d.getURL(), "<" + script.getNodeName() + ">", new Integer(line)});
          // Inline script.
          Node n = script.getFirstChild();
          if (n != null) {
            StringBuffer sb = new StringBuffer();
            while (n != null) {
              if (n.getNodeType() == Node.CDATA_SECTION_NODE || n.getNodeType() == Node.TEXT_NODE)
                sb.append(n.getNodeValue());
              n = n.getNextSibling();
            }
            reader = new StringReader(sb.toString());
          } else {
            continue;
          }
        }

        interpreter.evaluate(reader, desc);

      } catch (IOException e) {
        if (userAgent != null) {
          userAgent.displayError(e);
        }
        return;
      } catch (InterpreterException e) {
        System.err.println("InterpExcept: " + e);
        handleInterpreterException(e);
        return;
      } catch (SecurityException e) {
        if (userAgent != null) {
          userAgent.displayError(e);
        }
      }
    }
  }
Example #25
0
 public void transfer(String number) {
   ua.callTransfer(number, 0);
 }
Example #26
0
 /**
  * Checks that the script URLs and the document url are compatible. A SecurityException is thrown
  * if loading the script is not allowed.
  */
 protected void checkCompatibleScriptURL(String scriptType, ParsedURL scriptPURL) {
   userAgent.checkLoadScript(scriptType, scriptPURL, docPURL);
 }
Example #27
0
 public void togglebluetooth() {
   ua.bluetoothMediaApplication();
   Receiver.progress();
 }
Example #28
0
 /** Handles the given exception. */
 protected void handleInterpreterException(InterpreterException ie) {
   if (userAgent != null) {
     Exception ex = ie.getException();
     userAgent.displayError((ex == null) ? ie : ex);
   }
 }
Example #29
0
  /**
   * Parses the input row String into a Java object. For performance reasons this works in-place
   * updating the fields within this SnowPlowEventStruct, rather than creating a new one.
   *
   * @param row The raw String containing the row contents
   * @return true if row was successfully parsed, false otherwise
   * @throws SerDeException For any exception during parsing
   */
  public boolean updateByParsing(String row) throws SerDeException {

    // First we reset the object's fields
    nullify();

    // We have to handle any header rows
    if (row.startsWith("#Version:") || row.startsWith("#Fields:")) {
      return false; // Empty row will be discarded by Hive
    }

    final Matcher m = cfRegex.matcher(row);

    // 0. First check our row is kosher

    // -> is row from a CloudFront log? Will throw an exception if not
    if (!m.matches())
      throw new SerDeException("Row does not match expected CloudFront regexp pattern");

    // -> was generated by sp.js? If not (e.g. favicon.ico request), then silently return
    final String object = m.group(8);
    final String querystring = m.group(12);
    if (!(object.startsWith("/ice.png") || object.equals("/i") || object.startsWith("/i?"))
        || isNullField(querystring)) { // Also works if Forward Query String = yes
      return false;
    }

    // 1. Now we retrieve the fields which get directly passed through
    this.dt = m.group(1);
    this.tm = m.group(2); // CloudFront date format matches Hive's
    this.user_ipaddress = m.group(5);

    // 2. Now grab the user agent
    final String ua = m.group(11);
    try {
      this.useragent = decodeSafeString(ua);
    } catch (Exception e) {
      getLog().warn(e.getClass().getSimpleName() + " on { useragent: " + ua + " }");
    }

    // 3. Next we dis-assemble the user agent...
    final UserAgent userAgent = UserAgent.parseUserAgentString(ua);

    // -> browser fields
    final Browser b = userAgent.getBrowser();
    this.br_name = b.getName();
    this.br_family = b.getGroup().getName();
    final Version v = userAgent.getBrowserVersion();
    this.br_version = (v == null) ? null : v.getVersion();
    this.br_type = b.getBrowserType().getName();
    this.br_renderengine = b.getRenderingEngine().toString();

    // -> OS-related fields
    final OperatingSystem os = userAgent.getOperatingSystem();
    this.os_name = os.getName();
    this.os_family = os.getGroup().getName();
    this.os_manufacturer = os.getManufacturer().getName();

    // -> device/hardware-related fields
    this.dvce_type = os.getDeviceType().getName();
    this.dvce_ismobile = os.isMobileDevice();
    this.dvce_ismobile_bt = (byte) (this.dvce_ismobile ? 1 : 0);

    // 4. Now for the versioning (tracker versioning is handled below)
    this.v_collector = collectorVersion;
    this.v_etl = "serde-" + ProjectSettings.VERSION;

    // 5. Now we generate the event ID
    this.event_id = generateEventId();

    // 6. Now we dis-assemble the querystring.
    String qsUrl = null; // We use this in the block below, and afterwards
    List<NameValuePair> params = null; // We re-use this for efficiency
    try {
      params = URLEncodedUtils.parse(URI.create("http://localhost/?" + querystring), cfEncoding);

      // For performance, don't convert to a map, just loop through and match to our variables as we
      // go
      for (NameValuePair pair : params) {

        final String name = pair.getName();
        final String value = pair.getValue();

        final QuerystringFields field;
        try {
          field =
              QuerystringFields.valueOf(
                  name.toUpperCase()); // Java pre-7 can't switch on a string, so hash the string
        } catch (IllegalArgumentException e) {
          getLog().warn("Unexpected params { " + name + ": " + value + " }");
          continue;
        }

        try {
          switch (field) {
              // Common fields
            case E:
              this.event = asEventType(value);
              break;
            case IP:
              this.user_ipaddress = value;
              break;
            case AID:
              this.app_id = value;
              break;
            case P:
              this.platform = value;
              break;
            case TID:
              this.txn_id = value;
              break;
            case UID:
              this.user_id = value;
              break;
            case FP:
              this.user_fingerprint = value;
              break;
            case VID:
              this.visit_id = Integer.parseInt(value);
              break;
            case TSTAMP:
              // Replace our timestamp fields with the client's timestamp
              String[] timestamp = value.split(" ");
              this.dt = timestamp[0];
              this.tm = timestamp[1];
              break;
            case TV:
              this.v_tracker = value;
              break;
            case LANG:
              this.br_lang = value;
              break;
            case F_PDF:
              if ((this.br_features_pdf = stringToByte(value)) == 1) this.br_features.add("pdf");
              break;
            case F_FLA:
              if ((this.br_features_flash = stringToByte(value)) == 1) this.br_features.add("fla");
              break;
            case F_JAVA:
              if ((this.br_features_java = stringToByte(value)) == 1) this.br_features.add("java");
              break;
            case F_DIR:
              if ((this.br_features_director = stringToByte(value)) == 1)
                this.br_features.add("dir");
              break;
            case F_QT:
              if ((this.br_features_quicktime = stringToByte(value)) == 1)
                this.br_features.add("qt");
              break;
            case F_REALP:
              if ((this.br_features_realplayer = stringToByte(value)) == 1)
                this.br_features.add("realp");
              break;
            case F_WMA:
              if ((this.br_features_windowsmedia = stringToByte(value)) == 1)
                this.br_features.add("wma");
              break;
            case F_GEARS:
              if ((this.br_features_gears = stringToByte(value)) == 1)
                this.br_features.add("gears");
              break;
            case F_AG:
              if ((this.br_features_silverlight = stringToByte(value)) == 1)
                this.br_features.add("ag");
              break;
            case COOKIE:
              this.br_cookies = stringToBoolean(value);
              this.br_cookies_bt = (byte) (this.br_cookies ? 1 : 0);
              break;
            case RES:
              String[] resolution = value.split("x");
              if (resolution.length != 2) throw new Exception("Couldn't parse res field");
              this.dvce_screenwidth = Integer.parseInt(resolution[0]);
              this.dvce_screenheight = Integer.parseInt(resolution[1]);
              break;
            case CD:
              this.br_colordepth = value;
              break;
            case TZ:
              this.os_timezone = decodeSafeString(value);
              break;
            case REFR:
              this.page_referrer = decodeSafeString(value);
              break;
            case URL:
              qsUrl = pair.getValue(); // We might use this later for the page URL
              break;

              // Page-view only
            case PAGE:
              this.page_title = decodeSafeString(value);
              break;

              // Event only
            case EV_CA:
              this.ev_category = decodeSafeString(value);
              break;
            case EV_AC:
              this.ev_action = decodeSafeString(value);
              break;
            case EV_LA:
              this.ev_label = decodeSafeString(value);
              break;
            case EV_PR:
              this.ev_property = decodeSafeString(value);
              break;
            case EV_VA:
              this.ev_value = decodeSafeString(value);
              break;

              // Ecommerce
            case TR_ID:
              this.tr_orderid = decodeSafeString(value);
              break;
            case TR_AF:
              this.tr_affiliation = decodeSafeString(value);
              break;
            case TR_TT:
              this.tr_total = decodeSafeString(value);
              break;
            case TR_TX:
              this.tr_tax = decodeSafeString(value);
              break;
            case TR_SH:
              this.tr_shipping = decodeSafeString(value);
              break;
            case TR_CI:
              this.tr_city = decodeSafeString(value);
              break;
            case TR_ST:
              this.tr_state = decodeSafeString(value);
              break;
            case TR_CO:
              this.tr_country = decodeSafeString(value);
              break;
            case TI_ID:
              this.ti_orderid = decodeSafeString(value);
              break;
            case TI_SK:
              this.ti_sku = decodeSafeString(value);
              break;
            case TI_NA:
              this.ti_name = decodeSafeString(value);
              break;
            case TI_CA:
              this.ti_category = decodeSafeString(value);
              break;
            case TI_PR:
              this.ti_price = decodeSafeString(value);
              break;
            case TI_QU:
              this.ti_quantity = decodeSafeString(value);
              break;
          }
        } catch (Exception e) {
          getLog().warn(e.getClass().getSimpleName() + " on { " + name + ": " + value + " }");
        }
      }
    } catch (IllegalArgumentException e) {
      getLog().warn("Corrupted querystring { " + querystring + " }");
    }

    // 7. Choose the page_url
    final String cfUrl = m.group(10);
    if (!isNullField(cfUrl)) { // CloudFront didn't provide the URL as cs(Referer)
      this.page_url = cfUrl; // The CloudFront cs(Referer) URL
    } else {
      try {
        this.page_url =
            decodeSafeString(
                qsUrl); // Use the decoded querystring URL. Might be null (returned as null)
      } catch (Exception e) {
        getLog().warn(e.getClass().getSimpleName() + " on { qsUrl: " + qsUrl + " }");
      }
    }

    // 8. Finally handle the marketing fields in the page_url
    // Re-use params to avoid creating another object
    if (this.page_url != null) {
      params = null;
      try {
        params = URLEncodedUtils.parse(URI.create(this.page_url), "UTF-8");
      } catch (IllegalArgumentException e) {
        getLog().warn("Couldn't parse page_url: " + page_url);
      }
      if (params != null) {
        // For performance, don't convert to a map, just loop through and match to our variables as
        // we go
        for (NameValuePair pair : params) {

          final String name = pair.getName();
          final String value = pair.getValue();

          final MarketingFields field;
          try {
            field =
                MarketingFields.valueOf(
                    name.toUpperCase()); // Java pre-7 can't switch on a string, so hash the string
          } catch (IllegalArgumentException e) {
            // Do nothing: non-marketing related querystring fields are not an issue.
            continue;
          }

          try {
            switch (field) {
                // Marketing fields
              case UTM_MEDIUM:
                this.mkt_medium = decodeSafeString(value);
                break;
              case UTM_SOURCE:
                this.mkt_source = decodeSafeString(value);
                break;
              case UTM_TERM:
                this.mkt_term = decodeSafeString(value);
                break;
              case UTM_CONTENT:
                this.mkt_content = decodeSafeString(value);
                break;
              case UTM_CAMPAIGN:
                this.mkt_campaign = decodeSafeString(value);
                break;
            }
          } catch (Exception e) {
            getLog().warn(e.getClass().getSimpleName() + " on { " + name + ": " + value + " }");
          }
        }
      }
    }

    return true; // Successfully updated the row.
  }
Example #30
0
 /** Handles the given exception. */
 protected void handleSecurityException(SecurityException se) {
   if (userAgent != null) {
     userAgent.displayError(se);
   }
 }