在本地进行单信号工作,但是在生产中为什么不呢?

时间:2019-07-03 16:00:38

标签: java spring-boot

在本地onesignal工作中,它会在用户请求为我的系统上的房屋报价后向用户发送通知,但是当我将系统上载到生产环境中并订阅该按钮时,onesignal消失了,然后在单击时刷新页面它什么也不做,它在平台上订阅了onesignal,但是不发送通知

    package com.entendaantes.api.service;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Scanner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.entendaantes.api.config.property.EntendaAntesApiProperty;
import com.entendaantes.api.dto.UserAppAdministrator;
import com.entendaantes.api.model.UserApp;
import com.entendaantes.api.model.UserNotification;
import com.entendaantes.api.repository.UserAppRepository;

@Service
public class OneSignalService {
    @Autowired
    private UserAppRepository userAppRepository;

    @Autowired
    private EntendaAntesApiProperty entendaAntesApiProperty;

    private void pushNotification(UserNotification  userNotification) {

         try {
               String jsonResponse;

               HttpURLConnection con = getOneSignalConnection();                           
               getNotificationBytes(userNotification);

               // Se você souber de antemão a quantidade exata de bytes sendo gravados, você pode usá setFixedLengthStreamingMode()-los para definir exatamente essa quantidade de bytes, 
               //para que o Content-Lengthcabeçalho possa ser definido muito mais cedo e URLConnection liberar mais frequentementente
               con.setFixedLengthStreamingMode(getNotificationBytes(userNotification).length);

               //OutputStream é capaz de enviar dados a um determinado Stream
               OutputStream outputStream = con.getOutputStream();
               outputStream.write(getNotificationBytes(userNotification));

               int httpResponse = con.getResponseCode();

               if (  httpResponse >= HttpURLConnection.HTTP_OK
                  && httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
                  Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
                  jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                  scanner.close();
               }
               else {
                  Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
                  jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
                  scanner.close();
               }               
            } catch(Throwable t) {
               t.printStackTrace();
            }
    }

    public void userNotificationOneSignal(UserNotification  userNotification) {
    pushNotification(userNotification);
    }

    public void budgetCreated(UserNotification userNotification) {  
    List<UserAppAdministrator> users = userAppRepository.findByUserGroupIdAdministrator();
    users.forEach(admin -> {
        userNotification.getUserApp().setId(admin.getId());
        pushNotification(userNotification);
        });
    }

    public void budgetCreated(UserApp userApp) {
    }

    private byte[] getNotificationBytes(UserNotification userNotification) throws UnsupportedEncodingException {
        StringBuilder sb = stringBuilderNotification(userNotification);
        return sb.toString().getBytes("UTF-8");
    }

    private HttpURLConnection getOneSignalConnection() throws MalformedURLException, IOException {
        URL url = new URL("https://onesignal.com/api/v1/notifications");
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
           //Evitar cache da url se usarmos cache de URL, os arquivos que foram alterados não serão carregados completamente
           con.setUseCaches(false);

           //incluir corpo de solicitação   pretende gravar dados na conexão de URL.
           con.setDoOutput(true);

           // ler dados da conexão de URL.
           con.setDoInput(true);

           // propriedades de solicitação gerais são modificadas usando o método
           con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
           con.setRequestProperty("Authorization", "Basic " + entendaAntesApiProperty.getOneSignalRestApiKey());
           con.setRequestMethod("POST");
           //onbjeto de conexao
           return con;
    }

    private StringBuilder stringBuilderNotification(UserNotification userNotification) {
    StringBuilder builder = new StringBuilder();
        builder
        .append("{")
        .append("\"app_id\": \"" + entendaAntesApiProperty.getOneSignalAppId() +"\",");
            if (userNotification.getUserApp() != null && userNotification.getUserApp().getId() != null) {
                builder
                .append("\"include_external_user_ids\": [\"" + userNotification.getUserApp().getId() + "\"],");
            }
            else {
                builder
                .append("\"included_segments\": [\"professionals and companies\"],");
            }
        builder
        .append("\"data\": {\"foo\": \"bar\"},")
        .append("\"headings\": {\"en\": \"" + userNotification.getTitle() +"\"},")
        .append("\"contents\": {\"en\": \"" + userNotification.getDescription() +"\"},")
        .append("\"url\": \"" + userNotification.getLink() +"\",")
        .append("\"chrome_web_image\": \""+ userNotification.getImageNotification() +"\"")
        .append("}");
    return builder;
    }
}

0 个答案:

没有答案