次の方法で共有


バックエンドから REST API を使用する

「登録管理」で説明されているように、通常、アプリケーション バックエンドは通知を送信し、登録管理を実行する可能性があります。 Azure SDK for Node には Node.js 用の REST ラッパーが既に存在するため、このセクションでは Java の例を示します。

通知の送信

通知を送信するための REST API は、特殊なヘッダーを含む /yourHub/messages の単純な POST です。 プラットフォームネイティブ形式で通知を送信する場合、本文は送信するプラットフォーム固有の本文です。 追加のヘッダーは次のとおりです。

  • ServiceBusNotification-Format: プラットフォーム (ネイティブ通知を送信する場合) または "テンプレート" がテンプレート通知を送信することを指定します。

  • ServiceBusNotification-Tags (省略可能): 対象となる登録セットを定義するタグ (またはタグ式) を指定します。 このヘッダーが存在しない場合、通知ハブはすべての登録にブロードキャストされます。

その他のヘッダーは、 Notification Hubs REST API ドキュメント で指定されているように、プラットフォーム固有の機能でサポートされています。

次の Java コードは、(Apache HttpClient を使用して) Windows ストア アプリにネイティブ通知を送信します。

public Notification createWindowsNotification(String body) {
    Notification n = new Notification();
    n.body = body;

    n.headers.put("ServiceBusNotification-Format", "windows");

    if (body.contains("<toast>"))
        n.headers.put("X-WNS-Type", "wns/toast");
    if (body.contains("<tile>"))
        n.headers.put("X-WNS-Type", "wns/tile");
    if (body.contains("<badge>"))
        n.headers.put("X-WNS-Type", "wns/badge");

    if (body.startsWith("<")) {
        n.contentType = ContentType.APPLICATION_XML;
    }

    return n;
}

public void sendNotification(Notification notification, String tagExpression) {
    HttpPost post = null;
    try {
        URI uri = new URI(endpoint + hubPath + "/messages"+APIVERSION);
        post = new HttpPost(uri);
        post.setHeader("Authorization", generateSasToken(uri));

        if (tagExpression != null && !"".equals(tagExpression)) {
            post.setHeader("ServiceBusNotification-Tags", tagExpression);
    }

        for (String header: notification.getHeaders().keySet()) {
            post.setHeader(header, notification.getHeaders().get(header));
        }

        post.setEntity(new StringEntity(notification.getBody()));
        HttpResponse response = httpClient.execute(post);

        if (response.getStatusLine().getStatusCode() != 201) {
            String msg = "";
            if (response.getEntity() != null && response.getEntity().getContent() != null) {
                msg = IOUtils.toString(response.getEntity().getContent());
            }
            throw new RuntimeException("Error: " + response.getStatusLine() + " body: "+msg);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (post != null) post.releaseConnection();
    }
}

同様に、次のコードはテンプレート通知を送信します。

public Notification createTemplateNotification(Map<String, String> properties) {
    Notification n = new Notification();
    StringBuffer buf = new StringBuffer();
    buf.append("{");
    for (Iterator<String> iterator = properties.keySet().iterator(); iterator.hasNext();) {
        String key = iterator.next();
        buf.append("\""+ key + "\":\""+properties.get(key)+"\"");
        if (iterator.hasNext()) buf.append(",");
    }
    buf.append("}");
    n.body = buf.toString();

    n.contentType = ContentType.APPLICATION_JSON;

    n.headers.put("ServiceBusNotification-Format", "template");

    return n;
}

他のプラットフォームに通知を送信する方法の詳細については、「 Notification Hubs REST API」を参照してください。

登録の作成と更新

登録の作成と更新には、登録 XML 形式のシリアル化と逆シリアル化が必要です。 登録 API の作成 に関するトピックでは、さまざまな種類の登録を作成するための XML 形式 (すべてのプラットフォームのネイティブとテンプレート) を示します。

重要

XML 要素は、示されている正確な順序である必要があります。

Java で登録を作成し、単純な文字列連結を使用して登録 XML ペイロードを作成し、 Apache Digester を使用して結果を解析する例を次に示します。 前に説明したように、XML シリアル化または逆シリアル化のアプローチは機能します。

public Registration createRegistration(Registration registration) {
    HttpPost post = null;
    try {
        URI uri = new URI(endpoint + hubPath + "/registrations"+APIVERSION);
        post = new HttpPost(uri);
        post.setHeader("Authorization", generateSasToken(uri));

        StringEntity entity = new StringEntity(registration.getXml(),ContentType.APPLICATION_ATOM_XML);
        entity.setContentEncoding("utf-8");
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);

        if (response.getStatusLine().getStatusCode() != 200)
            throw new RuntimeException("Error: " + response.getStatusLine());

        return Registration.parse(response.getEntity().getContent());
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (post != null) post.releaseConnection();
    }
}

ネイティブ Windows 登録の getXml() メソッドは次のとおりです。

private static final String WNS_NATIVE_REGISTRATION = "<?xml version=\"1.0\" encoding=\"utf-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\"><content type=\"application/xml\"><WindowsRegistrationDescription xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.microsoft.com/netservices/2010/10/servicebus/connect\">{0}<ChannelUri>{1}</ChannelUri></WindowsRegistrationDescription></content></entry>";

public String getXml() {
    String xml = WNS_NATIVE_REGISTRATION.replaceFirst("\\{1\\}", channelUri.toString());
    xml = xml.replaceFirst("\\{0\\}", getTagsXml());
    return xml.toString();
}

登録 API の作成に関するトピックの例から、他の登録の種類のメソッド を簡単に 派生させることができます。

応答には、 RegistrationIdETagExpirationTime などの読み取り専用プロパティを含む、作成の結果が含まれます。 次のコード例では、 Apache Digester を使用して結果を解析します。

public static Registration parse(InputStream content) throws IOException,
            SAXException {
    Digester digester = new Digester();
    digester.addObjectCreate("*/WindowsRegistrationDescription",
                WindowsRegistration.class);

    digester.addCallMethod("*/RegistrationId", "setRegistrationId", 1);
    digester.addCallParam("*/RegistrationId", 0);
    digester.addCallMethod("*/ETag", "setEtag", 1);
    digester.addCallParam("*/ETag", 0);
    digester.addCallMethod("*/ChannelUri", "setChannelUri", 1);
    digester.addCallParam("*/ChannelUri", 0);
    digester.addCallMethod("*/Tags", "setTagsFromString", 1);
    digester.addCallParam("*/Tags", 0);
    digester.addCallMethod("*/BodyTemplate", "setBodyTemplate", 1);
    digester.addCallParam("*/BodyTemplate", 0);
    digester.addCallMethod("*/WnsHeader", "addHeader", 2);
    digester.addCallParam("*/WnsHeader/Header", 0);
    digester.addCallParam("*/WnsHeader/Value", 1);

    return digester.parse(content);
}

Create 呼び出しは、登録の取得、更新、または削除に使用される registrationId を返します。

Note

前のスニペットでは、WindowsRegistrationDescription という名前の Registration のサブクラスがあることを前提としています。

登録を更新するには、/yourhub/registrations/{registrationId}PUT 呼び出しを発行します。 If-Match ヘッダーは、常に上書きする ETag (オプティミスティック コンカレンシーをサポート) または単に "*" を提供するために使用されます。 If-Match ヘッダーが存在しない場合、操作は "upsert" を実行します (常に現在の登録を上書きするか、指定された registrationId に存在しない場合は作成します)。 次に例を示します。

public Registration updateRegistration(Registration registration) {
    HttpPut put = null;
    try {
        URI uri = new URI(endpoint + hubPath + "/registrations/"+registration.getRegistrationId()+APIVERSION);
        put = new HttpPut(uri);
        put.setHeader("Authorization", generateSasToken(uri));
        put.setHeader("If-Match", registration.getEtag()==null?"*":"W/\""+registration.getEtag()+"\"");

        put.setEntity(new StringEntity(registration.getXml(),ContentType.APPLICATION_ATOM_XML));
        HttpResponse response = httpClient.execute(put);

        if (response.getStatusLine().getStatusCode() != 200)
            throw new RuntimeException("Error: " + response.getStatusLine());

        return Registration.parse(response.getEntity().getContent());
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (put != null) put.releaseConnection();
    }
}

登録の削除 も同様の操作です。

登録の取得

登録を取得するときは、/registrations/{registrationId} に対して GET 呼び出しを発行します。 登録のコレクションは、次の REST API で指定されているように取得します。

その後、 $top パラメーターを指定できます。これにより、返される登録の数が制限されます。 そのクエリにさらに登録が存在する場合は、残りの登録を取得し続けるために後続の呼び出しに渡すことができる X-MS-ContinuationToken ヘッダーが返されます。 また、前に説明した API トピックに示すように、本文の形式は XML Atom フィードになりました。

minterastlib の次の Java コードは、タグを使用してすべての登録を取得します。

    private CollectionResult retrieveRegistrationByTag() {
        String queryUri = endpoint + hubPath + "/tags/"+tag+"/registrations"+APIVERSION;
    HttpGet get = null;
        try {
            URI uri = new URI(queryUri);
            get = new HttpGet(uri);
            get.setHeader("Authorization", generateSasToken(uri));
    
            HttpResponse response = httpClient.execute(get);
    
            if (response.getStatusLine().getStatusCode() != 200)
                throw new RuntimeException("Error: " + response.getStatusLine());
    
            CollectionResult result = Registration.parseRegistrations(response.getEntity().getContent());
            Header contTokenHeader = response.getFirstHeader("X-MS-ContinuationToken");
            if (contTokenHeader !=null) {
                result.setContinuationToken(contTokenHeader.getValue());
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (get != null) get.releaseConnection();
        }
    }

このコードでは、CollectionResult は、一連の登録を省略可能な継続トークンと共にカプセル化します。

次のコードでは 、Apache Digester を使用します。

public static CollectionResult parseRegistrations(InputStream content)
            throws IOException, SAXException {
    Digester digester = new Digester();

    // add all rules for parsing single registrations
    digester.addObjectCreate("feed", CollectionResult.class);
    digester.addSetNext("*/WindowsRegistrationDescription", "addRegistration");
    // add rules for other types of registrations (if required)

    return digester.parse(content);
}